-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
30 lines (27 loc) · 818 Bytes
/
Copy pathsolution.cpp
File metadata and controls
30 lines (27 loc) · 818 Bytes
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
class Solution
{
public:
vector<int> findDuplicates(vector<int> &arr)
{
int n = arr.size();
vector<int> ans;
// Traverse the array
for (int i = 0; i < n; i++)
{
int x = abs(arr[i]); // value in range [1, n]
int idx = x - 1; // mapped index
// If arr[idx] is positive, this is the first time we see x
if (arr[idx] > 0)
{
arr[idx] = -arr[idx]; // mark as seen by making it negative
}
else
{
// arr[idx] already negative -> x is seen before -> duplicate
ans.push_back(x);
}
}
// We can return in any order; driver will sort if needed.
return ans;
}
};