[Pointer speed] leetcode 286 Find the duplicate number

problem:

        Find whether there is a ring. Pointer 2 steps fast walking, slow down the pointer one step, it is present in the ring meet. Slow disposed away from the pointer s, the pointer quickly away 2s, loop length is s. If the starting position of the ring is d, the position of the pointer over a little slow in starting position where, as long as it can go back to step d walk starting position.

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;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11333750.html