## [Leetcode]442. Find All Duplicates in an Array(C++)

### 题目描述

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?

### 例子

Input: [4,3,2,7,8,2,3,1] Output: [2,3]

### 解题思路

#### 方法一

``````class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {

vector<int> duplicates;
int index = 0;
while (index < nums.size()) {

while (nums[index] != index + 1 && nums[index] != 0) {
int correct_index = nums[index] - 1;
if (nums[correct_index] == correct_index + 1) {
duplicates.push_back(nums[correct_index]);
nums[index] = 0;
break;
}
swap(nums[index], nums[correct_index]);
}
index++;
}

return duplicates;
}

};
``````
• 时间复杂度: O(n)
• 空间复杂度: O(1)

#### 方法二

``````class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {

vector<int> duplicates;
for (int i = 0; i < nums.size(); i++) {
int index = abs(nums[i]);
if (nums[index - 1] > 0) {
nums[index - 1] = -nums[index - 1];
} else {
duplicates.push_back(index);
}
}

return duplicates;
}

};
``````
• 时间复杂度: O(n)
• 空间复杂度: O(1)