打卡记录
寻找重复数(双指针)
链接
Floyd判圈法,先用快慢指针以不同速率进行移动,最终一定会出现相遇点,然后在使一指针从初始开始,两指针再以同步调移动,再次相遇的点一定为循环开始的点位。
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
};