-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindTheDuplicateNumber.java
More file actions
82 lines (71 loc) · 2.22 KB
/
FindTheDuplicateNumber.java
File metadata and controls
82 lines (71 loc) · 2.22 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package Algorithms.MiscAlgos;
import java.util.HashSet;
import java.util.Set;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 14 March 2025
*/
public class FindTheDuplicateNumber {
public static void main(String[] args) {
int[] nums = {1, 3, 4, 2, 2};
System.out.println("findDuplicate(nums) => " + findDuplicate(nums));
}
public static int findDuplicate(int[] nums) {
int slow = nums[0], fast = nums[0];
// Phase 1: Find the intersection point of the two runners
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// Phase 2: Find the entrance to the cycle
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
public static int findDuplicate2(int[] nums) {
int tortoise = nums[0];
int hare = nums[0];
// Phase 1: Find the intersection point of the two runners
while(true){
tortoise = nums[tortoise];
hare = nums[nums[hare]];
if(tortoise == hare)
break;
}
// Phase 2: Find the entrance to the cycle
tortoise = nums[0];
while(tortoise != hare){
tortoise = nums[tortoise];
hare = nums[hare];
}
return hare;
}
// FYI: 1 <= n <= 105 & 1 number is repeated more than once
public int findDuplicateUsingArr(int[] nums) {
int[] arr = new int[nums.length]; // or int[] arr = new int[100001];
for (int n: nums) {
if(arr[n] == 0) arr[n]=n;
else return n;
}
return 0;
}
// FYI: 1 <= n <= 105 & 1 number is repeated more than once
public int findDuplicateUsingArr2(int[] nums) {
boolean[] arr = new boolean[nums.length]; // or boolean[] arr = new boolean[100001];
for (int n: nums) {
if(arr[n]) return n;
else arr[n] = true;
}
return 0;
}
public int findDuplicateUsingSet(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int n: nums) {
if(!set.add(n)) return n;
}
return 0;
}
}