PU Find All Numbers Disappeared in an Array

Jan 01, 1970

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]

C Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
    int *res = malloc(numsSize * sizeof(int));
    *returnSize = 0;
    int i;
    for (i = 0; i < numsSize; i++) {
        int point;
        if (nums[i] < 0)  point = -nums[i] - 1;
        else point = nums[i] - 1;
        if (nums[point] > 0) nums[point] = -nums[point];
    }
    for (i = 0; i < numsSize; i++) {
        if (nums[i] > 0) res[(*returnSize)++] = i + 1;
    }
    return res;
}

Summary:

  • This is an experience, grasp it.

LeetCode: 448. Find All Numbers Disappeared in an Array