LeeCode 442. Find All Duplicates in an Array题解

来源:互联网 发布:进击的巨人漫画软件 编辑:程序博客网 时间:2024/06/04 19:15

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?

中文 :给定数组a,1<=a[i]<=n,每个元素至多出现2次,找出出现2次的元素。

解 :

因为a的大小也是n,所以如果把a看成抽屉,把抽屉i放元素i+1(下标起始不一致),那么必有抽屉必须放不为i+1的元素,找出这些抽屉输出。

如何找出这些抽屉呢?我们遍历一次数组,每次把元素i放进它对应的位置,遍历完后便有最多元素归位(数学证明略)

代码:

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




原创粉丝点击