LeeCode 287 fast and slow pointer

Title

Portal LeeCode 287

answer

Think of the index and value of a sequence as the value and pointer of a linked list. Consider index 0 0 non-repeating number, the value at the index of the number cannot point to itself, and so on, until the repeated number is encountered and then points to the node traversed; consider the index 0 0 is the case of repeated numbers, when the nodes all point to themselves; all can judge the ring to find the node that enters the ring to solve.

The judgment ring uses fast and slow pointers, and the speed difference is 1 1 Ensure that the fast pointer can catch up with the slow pointer when a ring occurs; at this time, the distance between the meeting position and the starting point is the same as that of the node entering the ring in the forward direction.

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int f = 0, s = 0;
        do{
            f = nums[nums[f]];
            s = nums[s];
        }while(f != s);
        int l = 0, r = s;
        while(l != r){
            l = nums[l];
            r = nums[r];
        }
        return r;
    }
};
Published 110 original articles · Like1 · Visits 2038

Guess you like

Origin blog.csdn.net/neweryyy/article/details/105567094