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.
s思路:
1. 边界很清楚。元素个数n+1个,数值大小1~n,且只有一个重复的元素,问:重复的是哪个数?
2. 不可否认,第一次做这道题时的印象太深刻,看到这道题,记忆就浮现出来,简直无法静下心思考。这道题就是用快慢指针的做法,因为把这个数组看成是链表,而相同的元素在效果上导致cycle,所以用快慢指针来检测cycle.例如:
上图:坐标0的值为1,而坐标1的值为2,坐标2值为3,坐标3的值为4,坐标4的值为2,注意看:又回到了坐标2,坐标2访问了两次,也就是说接下来就是循环了。
3. 为什么可以想到这个方法? 怎么就联想到了?把坐标和坐标的数交错的放在一起作为链表的元素,而且是有cycle的链表。你看,不但给一个链表能遍历,即使不是明着给链表,像这个题,也要从这种特殊性中看出链表,也就是说链表除了看得到的,还有看不到的,能从元素和坐标的这种强的对应关系中看出链表,而且是有cycle的链表,就是本事了!而且,一旦看出是有cycle的链表,问题就立马解决了!
4. 对这种一时半会还不知道怎么想到的方法,要欣赏之、继续思考和学习之!
class Solution {
public:
int findDuplicate(vector<int>& nums) {
//
int slow=0,fast=nums[0];
while(slow!=fast){
slow=nums[slow];
fast=nums[nums[fast]];
}
fast=0;
slow=nums[slow];
while(slow!=fast){
slow=nums[slow];
fast=nums[fast];
}
return slow;//bug:不能写return nums[slow];
//因为如上图,cycle相遇的地方就是重复值
}
};