-
Notifications
You must be signed in to change notification settings - Fork 0
/
442.find-all-duplicates-in-an-array.cpp
48 lines (47 loc) · 1.3 KB
/
442.find-all-duplicates-in-an-array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
// version 1: twice for loop
/*
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i != nums[i] - 1) {
if (nums[nums[i] - 1] != nums[i]) {
swap(nums[nums[i] - 1], nums[i]);
i--;
}
}
}
for (int i = 0; i < nums.size(); i++) {
if (nums[i] - 1 != i) {
res.push_back(nums[i]);
}
}
return res;
*/
// version 2: once loop, use nums set tag.
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i != nums[i] - 1 && nums[i] != -1) {
if (nums[nums[i] - 1] != nums[i]) {
swap(nums[nums[i] - 1], nums[i]);
i--;
} else {
res.push_back(nums[i]);
nums[i] = -1;
}
}
}
return res;
// or like this
/*
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;
*/
}
};