[leetcode]268. Missing Number

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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容