您的位置:首页 > 其它

LeetCode - 442 - Find All Duplicates in an Array

2017-07-11 11:05 573 查看
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]


自己的思路是用异或写,从头开始异或,异或到为0时说明出现过,然后发现大大的bug23333(1,2,3异或为0,尴尬)

后来发现漏了一个重要的条件,
 1 ≤ a[i] ≤ n (n =
size of array),   嗯。。。

如果不卡空间的话,用unordered_map倒也是不错的选择

关于正解,a[i]的范围真的是很巧妙,正解看起来超优雅的哎。

一直做交换,复杂度最多也只会到2*n,常数不大,基本还是O(n)的复杂度

class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ans;
for (int i = 0; i < nums.size(); ) {
if (nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]);
else i++;
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != i + 1) ans.push_back(nums[i]);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: