-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathFindtheDuplicateNumber.java
84 lines (58 loc) · 1.41 KB
/
FindtheDuplicateNumber.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
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
83
84
/*
Source: https://leetcode.com/problems/find-the-duplicate-number/
3 Approaches
1st Approach(By using extra space)
Time: O(n), where n is the length of the given array(nums)
Space: O(n), hashset is needed to add each num in nums
*/
class Solution {
public int findDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for(int num : nums) {
if(!seen.add(num)) {
return num;
}
}
return -1;
}
}
/*
Approach 2 (By modifying array)
Time: O(n), where n is the length of the given array(nums)
Space: O(1), in-place
*/
class Solution {
public int findDuplicate(int[] nums) {
for(int num : nums) {
int curr = Math.abs(num);
if(nums[curr] < 0) {
return curr;
// return -nums[i];// will not work for cases like [2,1,4,4,3], but will work for [3,4,2,1,4]
}
nums[curr] = -nums[curr];
}
return -1;
}
}
/*
Approach 3 (Using Floyd's cycle detection algorithm(Tortoise and Hare or Slow and Fast pointer))
Time: O(n), where n is the length of the given array(nums)
Space: O(1), in-place
*/
class Solution {
public int findDuplicate(int[] nums) {
int slow = nums[0];
int fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while(fast != slow);
fast = nums[0];
while(fast != slow) {
fast = nums[fast];
slow = nums[slow];
}
return fast;
// return slow;
}
}