题目链接:https://leetcode.com/problems/find-the-duplicate-number/description/
题目:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than
O(n2)
. - There is only one duplicate number in the array, but it could be repeated more than once.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:
这道题,老实说我只想到了肯定会超时的暴力解,然后查看了标准solution,发现用到了一个定理Floyd 判圈定理,只要了解该定理,本题就变得很容易,
正如定理所说:“如果有限状态机或者链表上存在环,那么从同一起点以不同速度前进的两个指针必定会在某个时刻相遇”。这个定理可以判环,至于重复点,假设相遇点为M,那么令指针h从M出发,同时指针t从起点以相同的速度出发,那么相遇点就是环起点,也就是本题的重复点。
代码:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0;
int fast = 0;
while(true) {
slow = nums[slow];
fast = nums[nums[fast]];
if(slow == fast) break;
}
int t = 0;
while(true) {
t = nums[t];
slow = nums[slow];
if(slow == t) break;
}
return slow;
}
};