# 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]
``````

``````class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
int idx = abs(nums[i]) - 1;
if (nums[idx] < 0) res.push_back(idx + 1);
nums[idx] = -nums[idx];
}
return res;
}
};
``````

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

``````class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
int n = nums.size();
for (int i = 0; i < n; ++i) {
nums[(nums[i] - 1) % n] += n;
}
for (int i = 0; i < n; ++i) {
if (nums[i] > 2 * n) res.push_back(i + 1);
}
return res;
}
};
``````

Find the Duplicate Number

https://discuss.leetcode.com/topic/64759/very-simple-c-solution

https://discuss.leetcode.com/topic/64735/java-simple-solution/2

https://discuss.leetcode.com/topic/64744/2-pass-o-1-space-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation