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