美文网首页
448. Find All Numbers Disappeare

448. Find All Numbers Disappeare

作者: larrymusk | 来源:发表于2017-12-05 11:24 被阅读0次
    Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
    
    Find all the elements of [1, n] inclusive that do not appear in this array.
    
    Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
    
    Example:
    
    Input:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [5,6]
    
    
    int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
    
        int * hash = calloc(numsSize, sizeof(int));
        *returnSize = 0;
        int * ret = calloc(*returnSize, sizeof(int));
        for(int i = 0; i < numsSize;i++)
            hash[nums[i]-1]++;
        
        for(int i = 0; i < numsSize;i++){
            if(hash[i] == 0){
                *returnSize = *returnSize+1;
                ret = realloc(ret, (*returnSize)*(sizeof(int)));
                ret[*returnSize-1] = i+1;
            }
        }
        
        return ret;
    }
    
    //nums[abs(nums[i]) - 1] = -abs(nums[abs(nums[i]) - 1]);
    int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
        int count = 0;
        int *array = calloc(numsSize, sizeof(int));
        for(int i = 0; i < numsSize; i++)
            nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1]);
        for(int i = 0; i < numsSize; i++)
            if(nums[i] >0){
            //i+1 found
            array[count++] = i+1;
        }
    
    *returnSize = count;
    return array;
    }
    
    
    

    相关文章

      网友评论

          本文标题:448. Find All Numbers Disappeare

          本文链接:https://www.haomeiwen.com/subject/ghwqixtx.html