Likou 448. Find all the missing numbers in the array

topic

[Portal]

Given an integer array with a range of 1 ≤ a[i] ≤ n (n = array size), some elements in the array appear twice, and some only appear once.
Find all the numbers in the range [1, n] that do not appear in the array.
Can you accomplish this task without using extra space and the time complexity is O(n)? You can assume that the returned array is not included in the extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:

[5,6]

Source: LeetCode

Problem solving

template

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize){
    
    

}

analysis

The requirement of the question is to find that for an array of length n in the array, the original reason is to keep the natural numbers of 1-n in the array. If there are qualified natural numbers that are not included, the array composed of natural numbers of that type is returned.

logical analysis

The conditions are available, the elements are all within a range between 1 and n, so we can create a new array with subscript +1 to correspond to the range in the original array. The new array is set to new, which is represented by new[0] It is the number of occurrences of 1 in the original array.
Insert picture description here
According to the new array returned at the end, if it is 0, it does not appear, and the corresponding subscript +1 is the number that does not appear;
Insert picture description hereon this basis, some logical changes are made, because it is best not to create a new array for the process. Do not build, so as to better avoid wasting resources.
The reference code is as follows: [Portal]

Code:

int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
    
    
   for (int i = 0; i < numsSize; i++) {
    
    
       int x = (nums[i] - 1) % numsSize;
       nums[x] += numsSize;
   }
   int* ret = malloc(sizeof(int) * numsSize);
   *returnSize = 0;
   for (int i = 0; i < numsSize; i++) {
    
    
       if (nums[i] <= numsSize) {
    
    
           ret[(*returnSize)++] = i + 1;
       }
   }
   return ret;
}

Guess you like

Origin blog.csdn.net/qq_44922487/article/details/113798881