Skip to content

Commit d666e02

Browse files
committed
Find all duplicates in an array(solved)
1 parent 339399c commit d666e02

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
https://leetcode.com/problems/find-all-duplicates-in-an-array/
3+
*/
4+
5+
class Solution {
6+
public List<Integer> findDuplicates(int[] nums) {
7+
//we are solving this question using cyclic sort
8+
int i=0;
9+
while(i<nums.length){
10+
int correct=nums[i]-1;
11+
if(nums[i]!=nums[correct]){
12+
swap(nums,i,correct);// this line will call the function swap
13+
}
14+
else{
15+
i++;
16+
}
17+
}
18+
List<Integer> ans=new ArrayList<>();
19+
for(int j=0;j<nums.length;j++){
20+
if(nums[j]!=j+1){
21+
ans.add(nums[j]);//here we are adding elements in array
22+
}
23+
}
24+
return ans;
25+
}
26+
void swap(int[] arr,int b,int a){ // by creating 1 temp varible to swap the values of variables
27+
int temp=arr[a];
28+
arr[a]=arr[b];
29+
arr[b]=temp;
30+
}
31+
}

0 commit comments

Comments
 (0)