287. Find the Duplicate Number
problem description
Input: [1,3,4,2,2]
Output: 2Input: [3,1,3,4,2]
Output: 3algorithm thought
code
algorithm analysis
Last updated
Input: [1,3,4,2,2]
Output: 2Input: [3,1,3,4,2]
Output: 3Last updated
class Solution {
public:
int findDuplicate(vector<int>& nums) {
if(nums.size()<=1)
return -1;
int slow=nums[0];
int fast=nums[nums[0]];
while(slow!=fast){
slow=nums[slow];
fast=nums[nums[fast]];
}
slow=0;
while(slow!=fast){
slow=nums[slow];
fast=nums[fast];
}
return slow;
}
};