Skip to content

Commit 82ab12f

Browse files
authored
using floyd cycle detection: slow & fast pointers
1 parent e120afe commit 82ab12f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Find the Duplicate Number

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
int findDuplicate(vector<int>& nums)
4+
{
5+
if(nums.empty()) return 0;
6+
7+
int slow = nums[0], fast=nums[0];
8+
9+
do
10+
{
11+
slow = nums[slow];
12+
fast = nums[nums[fast]];
13+
}while(slow!=fast);
14+
15+
slow = nums[0];
16+
17+
while(fast != slow)
18+
{
19+
slow=nums[slow];
20+
fast=nums[fast];
21+
}
22+
return fast;
23+
24+
}
25+
};

0 commit comments

Comments
 (0)