287. Find the Duplicate Number
Solution
class Solution {
public:
int findDuplicate(vector<int>& nums) {
// Find the intersection point of the two runners.
int tortoise = nums[0];
int hare = nums[0];
do {
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
// Find the "entrance" to the cycle.
tortoise = nums[0];
while (tortoise != hare) {
tortoise = nums[tortoise];
hare = nums[hare];
}
return hare;
}
};
Complexity
- Time Complexity: O(N), where N is the size of
nums
. - Space Complexity: O(1).