forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode442.java
More file actions
40 lines (33 loc) · 852 Bytes
/
Leetcode442.java
File metadata and controls
40 lines (33 loc) · 852 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
31
32
33
34
35
36
37
38
39
40
package com.company;
import java.util.*;
public class Leetcode442 {
public static void main(String[] args) {
int arr[]={4,3,2,7,8,2,3,1};
List<Integer> ans=duplicate(arr);
System.out.println(ans);
}
static List<Integer> duplicate(int[] arr){
int i=0;
while(i<arr.length){
int correctIndex=arr[i]-1;
if(arr[i]!=arr[correctIndex]){
swap(arr,i,correctIndex);
}
else {
i++;
}
}
List<Integer> ans=new ArrayList<>();
for(int j=0;j<arr.length;j++){
if(arr[j]!=j+1){
ans.add(arr[j]);
}
}
return ans;
}
static void swap(int[] arr, int a, int b){
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
}