Skip to content

Commit c3c15f7

Browse files
authored
Merge pull request #858 from notauserx/Create-287-Find-the-Duplicate-Number.cs
Create 287-Find-the-Duplicate-Number.cs
2 parents 78caaa8 + 24413ba commit c3c15f7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: csharp/287-Find-the-Duplicate-Number.cs

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class Solution {
2+
public int FindDuplicate(int[] nums) {
3+
return floydAlgorithm(nums);
4+
// return arrayAsHashMapIterative(nums);
5+
}
6+
7+
private int floydAlgorithm(int[] nums) {
8+
int slow = 0, fast = 0;
9+
10+
while(true) {
11+
slow = nums[slow];
12+
fast = nums[nums[fast]];
13+
if (slow == fast)
14+
break;
15+
}
16+
17+
var slow2 = 0;
18+
19+
while(true) {
20+
slow = nums[slow];
21+
slow2 = nums[slow2];
22+
if (slow == slow2)
23+
return slow;
24+
}
25+
26+
return 0;
27+
}
28+
29+
private int arrayAsHashMapIterative(int[] nums) {
30+
while(nums[0] != nums[nums[0]]) {
31+
int nxt = nums[nums[0]];
32+
nums[nums[0]] = nums[0];
33+
nums[0] = nxt;
34+
}
35+
36+
return nums[0];
37+
}
38+
}

0 commit comments

Comments
 (0)