Missing Number
描述:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example1:
Input: [3,0,1]
Output: 2
Example2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
思路:時間要求為線性,用空間換時間。memset函數(shù)將申請的所有空間賦值為0。遍歷數(shù)組,給數(shù)組中存在的值對應(yīng)的新數(shù)組位置賦值為1,再遍歷一次新數(shù)組,返回值不為1的位置標(biāo)號即為結(jié)果。
問題:一開始想要給新數(shù)組賦值為其標(biāo)號值,但是經(jīng)過同學(xué)修改這樣賦值為1更為清晰一些。還遇到了不進(jìn)入for循環(huán)的情況,是memset函數(shù)的傳入值寫的不對。
代碼:
int missingNumber(int* nums, int numsSize) {
int i,j;
int n= numsSize+1;
int m= numsSize;
int *p=NULL;
int temp;
int res = -1;
p=(int *)malloc(n*sizeof(int));
memset(p,0,sizeof(int)*n);
for(i=0;i<m;i++){
p[nums[i]]=1;
}
for(j=0;j<n;j++){
if(p[j]!=1)
return j;
}
return res;
}