leetcode刷题系列--442. Find All Duplicates in an Array

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

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

Output:
[2,3]

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> findDuplicates(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(nums[i]);
        }
        return res;
    }
};
一遍遍的交换,直到所有的数字都在自己所在的位置,当出现不在自己位置的数字时,说明该数字是有重复的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章