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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章