Skip to content

Commit

Permalink
Find All Duplicates in an Array
Browse files Browse the repository at this point in the history
  • Loading branch information
Pranjal authored Aug 28, 2017
1 parent dfc98cb commit 0b543eb
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions FindAllDuplicatesInAnArray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
public:
void swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}

vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size(), i = 0;

while(i < n){
while((nums[i]-1 != i) && (nums[i] != nums[nums[i]-1])){
swap(nums[i], nums[nums[i]-1]);
}
i++;
}

vector<int> ans;

for(int i = 0; i < n; i++){
if(nums[i]-1 != i){
ans.push_back(nums[i]);
}
}

if(ans.size()){
sort(ans.begin(), ans.end());
}

return ans;
}
};

0 comments on commit 0b543eb

Please sign in to comment.