[快慢指针]leetcode 286 Find the duplicate number

problem:

        查找是否存在环。快指针走2步,慢指针走1步,相遇则存在环。设慢指针走了路程s,则快指针走了2s,环长度为s。若环的起始位置为d,则慢指针的位置在起始位置过一点的地方,它只要再走d步又可以回到起始位置 。

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
    int slow=0;
    int far=0;
    int n=nums.size();
// s,2s 2s=s+l d+t=s
// walk t, plus d get complete circle
    while(true){
        slow=nums[slow];
        far=nums[nums[far]];
        if(slow==far)break;
    }
    int head=0;
    while(head!=slow) {
        head=nums[head];
        slow=nums[slow];
    }
    return head;
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11333750.html
今日推荐