leetcode刷题系列 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]

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes


class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int len = nums.size();
        vector<int> res;
        for(int i = 0; i < len; ++i)
        {
            if(nums[i] == i + 1)
                continue;
            else
            {
                while(nums[i] != i + 1 && nums[nums[i] - 1] != nums[i])
                {
                    int tmp = nums[i];
                    nums[i] = nums[tmp - 1];
                    nums[tmp - 1] = tmp;
                }
            }
        }
        
        for(int i = 0; i < len; ++i)
        {
            if(nums[i] != i + 1)
                res.push_back(i + 1);
        }
        return res;
    }
};


不停的做交换操作 直到每个位置跟该位置处的元素值一致为止。
发布了119 篇原创文章 · 获赞 17 · 访问量 18万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章