-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.java
39 lines (34 loc) · 1017 Bytes
/
solution.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
class Solution {
public int findDuplicate(int[] nums) {
// //Perform Cyclic Sort
// for(int i = 0; i < nums.length;){
// int num = nums[i];
// //If already on right place move forward
// if(num == i + 1){
// i++;
// continue;
// }
// int realIdx = nums[i] - 1;
// //If number is already there
// if(nums[realIdx] == num)
// return num;
// //Swap the numbers
// nums[i] = nums[realIdx];
// nums[realIdx] = num;
// }
// return -1;
//Perform Floyd's Cycle Detection
int slow = 0, fast = 0;
do{
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
//Check the cycle
int i = 0;
while(i != slow){
i = nums[i];
slow = nums[slow];
}
return slow;
}
}