Given an array of n+1
integers, each in the range 1
to n
, find an integer that is repeated.
I was asked this at a job intervi
We use circle detection's idea to solve this problem.
All we need to do is first find the begin of the circle and then find the duplicated one in the circle.
Here's the code in c++:
int findDuplicate(vector& nums) {
int slow = nums[0];
int fast = nums[nums[0]];
while(slow != fast){
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while(slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}