-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_All_The_Duplicates.cpp
More file actions
55 lines (48 loc) · 1.03 KB
/
Find_All_The_Duplicates.cpp
File metadata and controls
55 lines (48 loc) · 1.03 KB
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
49
50
51
52
53
54
55
/* We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space.
Example 1:
Input: [3, 4, 4, 5, 5]
Output: [4, 5]
*/
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void swap(vector<int> &arr, int i, int j)
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
vector<int> find_all_duplicates(vector<int> &nums)
{
int i=0;
vector<int> result;
while(i<nums.size())
{
if(nums[i]!=nums[nums[i]-1])
{
swap(nums,i,nums[i]-1);
}
else
{
i++;
}
}
vector<int> duplicates;
for(int i=0;i<nums.size();i++)
{
if(nums[i]!=i+1)
{
duplicates.push_back(nums[i]);
}
}
return duplicates;
}
int main()
{
vector<int> input={1,2,3,3,2,4};
for(auto res:find_all_duplicates(input))
{
cout<<res<<",";
}
}