LeetCode No.448 Find All Numbers Disappeared in an Array

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]

===================================================================

題目鏈接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

題目大意:給定一個長度爲n的數組,其中1 ≤ a[i] ≤ n ,找出所有不在數組中的[1, n],要求使用時間複雜度爲O(N),空間複雜度爲O(1)的算法

思路:先對數組進行重組,使得所有存在的i + 1都構成nums[i] = i + 1,剩下不符合這個等式的就是不存在的。

參考代碼:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int n = nums.size() ;
        for ( int i = 0 ; i < n ; i ++ )
        {
            while ( nums[nums[i]-1] != i )
            {
                if ( nums[i] == nums[nums[i]-1] )
                    break ;
                swap ( nums[i] , nums[nums[i]-1] ) ;
            }
        }
        vector <int> ans ;
        for ( int i = 0 ; i < n ; i ++ )
            if ( nums[i] != i + 1 )
                ans.push_back ( i + 1 ) ;
        return ans ;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章