442. Find All Duplicates in an Array (array)

来源:互联网 发布:文明太空 知乎 编辑:程序博客网 时间:2024/04/27 20:27
  1. Find All Duplicates in an Array Add to List QuestionEditorial
    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]

//依然采用交换法则,不断将数据交换至其应该所在的位置上,同448题思路一样vector<int> findDuplicates(vector<int>& nums) {        int len = nums.size();        if(len<=1)        {            return (vector<int> ());        }        vector<int> result;        for(int i=0; i<len;i++)        {            if(nums[i] == i + 1)            {                continue;            }            else            {                while(nums[nums[i] - 1] != nums[i])                {                    int temp = nums[nums[i] - 1];                    nums[nums[i] - 1] = nums[i];                    nums[i] = temp;                }            }        }        for(int i = 0; i<len; i++)        {            if(nums[i] != i+1)            {                result.push_back(nums[i]);            }        }        return result;    }
0 0