[LeetCode] 448. Find all the missing numbers in the array (C++)

1 topic description

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.

2 Example description

Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]

3 Problem solving requirements

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.

4 Problem-solving ideas

Simply take two vectors, time and space should be super, but it is very simple to make.

5 Detailed source code (C++)

class Solution {
    
    
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
    
    
        vector<int> has ;
        vector<int> res ;
        has.resize( nums.size() ) ; //开一个nums.size()肯定是够用的
        for ( int i = 0 ; i < nums.size() ; i ++ )
        {
    
    
            has[nums[i] -1] ++ ; //将原数组的1放在has[0]的位置,以此类推
        }
        for ( int i = 0 ; i < nums.size() ; i ++ )
        {
    
    
            if ( has[i] == 0 )
            {
    
    
                res.push_back( i + 1 ) ;
            }
        }
        return res ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114435174