448. Find All Numbers Disappeare

2017-12-05  本文已影响0人  larrymusk
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;
}


上一篇 下一篇

猜你喜欢

热点阅读