题目:287. 寻找重复数
大佬题解
精髓在此
C++版本:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n=nums.size();
int slow=0,fast=0;
do{
slow=nums[slow];
fast=nums[nums[fast]];
}while(slow!=fast);
int p=0;
while(p!=slow){
p=nums[p];
slow=nums[slow];
}
return p;
}
};
JAVA 版本:
class Solution {
public int findDuplicate(int[] nums) {
int slow=0,fast=0;
do{
slow=nums[slow];
fast=nums[nums[fast]];
}while(slow!=fast);
int p=0;
while(p!=slow){
p=nums[p];
slow=nums[slow];
}
return p;
}
}