# LeetCode-442. Find All Duplicates in an Array

## Description

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]

## Solution 1(C++)

static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0;}();
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i=0; i<nums.size(); i++){
if(nums[abs(nums[i])-1] < 0) res.push_back(abs(nums[i]));
else nums[abs(nums[i])-1] = 0-nums[abs(nums[i])-1];
}
return res;
}
};

## Solution 2(C++)

static const auto _____ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();

class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
// 思路：对数字加数组长度不影响其对数组长度求余的值
// 如果数组中的元素最终超过2倍数组长度大小的话说明该元素对应的位置的数字出现了两次
int size = nums.size();
vector<int> result;
for(int i = 0; i < size; i++){
nums[(nums[i] - 1) % size] += size;
}

for(int i = 0; i < size; i++){
if(nums[i] > 2*size) result.push_back(i+1);
}
return result;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120