- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLeetcode442.java
40 lines (33 loc) · 852 Bytes
/
Leetcode442.java
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
packagecom.company;
importjava.util.*;
publicclassLeetcode442 {
publicstaticvoidmain(String[] args) {
intarr[]={4,3,2,7,8,2,3,1};
List<Integer> ans=duplicate(arr);
System.out.println(ans);
}
staticList<Integer> duplicate(int[] arr){
inti=0;
while(i<arr.length){
intcorrectIndex=arr[i]-1;
if(arr[i]!=arr[correctIndex]){
swap(arr,i,correctIndex);
}
else {
i++;
}
}
List<Integer> ans=newArrayList<>();
for(intj=0;j<arr.length;j++){
if(arr[j]!=j+1){
ans.add(arr[j]);
}
}
returnans;
}
staticvoidswap(int[] arr, inta, intb){
inttemp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
}