-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-1.java
61 lines (40 loc) · 1.12 KB
/
Problem-1.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
/**
* @author AkashGoyal
* @date 27/05/2021
*/
/**
--------------------- Problem----------->> Find the Duplicate Number
Problem Link :- https://leetcode.com/problems/find-the-duplicate-number/
*/
class Solution {
public int findDuplicate(int[] nums) {
// s(start index) ->d(loop start) ->c(colide) ->d(loop start)
// x y z=x
// sped f = 2 * speed s
// x + y+z+y = 2(x+y)
// x+y+z+y = x + x +y+ +y
// z= x
//start with same index
int slow=nums[0];
int fast=nums[0];
//move one point ahead
slow=nums[slow];
//move two point ahead
fast=nums[nums[fast]];
//detecting cycle
while(fast!=slow)
{
fast=nums[nums[fast]];
slow=nums[slow];
}
// putting slow at start
slow=nums[0];
//wherever they colide return that element
while(fast!=slow)
{
fast=nums[fast];
slow=nums[slow];
}
return slow;
}
}