-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay3.java
More file actions
35 lines (26 loc) · 909 Bytes
/
Copy pathDay3.java
File metadata and controls
35 lines (26 loc) · 909 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
public class FindDuplicateNumber {
public static int findDuplicate(int[] arr) {
int slow = arr[0];
int fast = arr[0];
do {
slow = arr[slow];
fast = arr[arr[fast]];
} while (slow != fast);
slow = arr[0];
while (slow != fast) {
slow = arr[slow];
fast = arr[fast];
}
return slow;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 4, 2, 2};
System.out.println("Duplicate: " + findDuplicate(arr1));
int[] arr2 = {3, 1, 3, 4, 2};
System.out.println("Duplicate: " + findDuplicate(arr2));
int[] arr3 = {1, 1};
System.out.println("Duplicate: " + findDuplicate(arr3));
int[] arr4 = {1, 4, 4, 2, 3};
System.out.println("Duplicate: " + findDuplicate(arr4));
}
}