LeetCode 287. Find the Duplicate Number 解题报告
题目描述
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.
示例
[1,1]
return 1
限制条件
- 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.
解题思路
我的思路:
很关键的一点,要知道这个数组其实就是一个带环的链表,要找的重复元素就是环的入口。
比如[1,2,3,4,5,6,3]就如同下图:
而带环的链表有个性质:假设环的长度是n,那么p1从链表起始出发,p2从链表头部移动n次的位置出发,同时移动两个指针,当它们的值相同时,它们就位于环的入口元素。比如,上述例子中,环的长度是4,p1从0开始,p2从4开始,当它们同时移动了3次后,它们的值都为3。
而怎么才能知道环的长度?我们可以通过设置p1和p2移动的快慢来获得:
设置p1和p2两个指针,p1每次移动1步,p2每次移动2步,当它们第一次相遇时,它们位于环内的某个元素,此时,p2比p1多走了n步,n就是环的长度。
所以代码实现时就是先通过p1移动1步和p2移动2步来获取环的长度n,然后利用上述性质,让p1从起始位置开始,p2从偏离起始n的位置开始,同时移动两个指针,当它们相同时就得到了重复的元素。
参考思路
大牛们第一步也是移动两个速度不一样的指针,直到它们在环内的某一点k相遇。如下图
此时我们来分析一下两个指针走过的距离(p1走1步,p2走2步):
p1: m + k
p2: m + k+ n - 1
有
2(m+k) = m + k + n - 1
m + k = n - 1
m = n - k - 1
而n - k - 1刚好就是从环内离起点k位置出发,绕大的半圆回到环起点的距离。
此时p1和p2都是在k位置,所以直接让p1留在原位,而p2设为起点出发,两个指针同时移动,每次1步,再次相遇就刚好在环起点位置,也就是重复元素所在位置。
代码
我的代码
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int p1 = nums[0];
int p2 = nums[nums[0]];
int len = 1;
while (p1 != p2) {
p1 = nums[p1];
p2 = nums[nums[p2]];
len++;
}
p1 = nums[0];
for (; len >= 0; len--)
p2 = nums[p2];
while (p1 != p2) {
p1 = nums[p1];
p2 = nums[p2];
}
return p1;
}
};
参考代码
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int p1 = nums[0];
int p2 = nums[nums[0]];
while (p1 != p2) {
p1 = nums[p1];
p2 = nums[nums[p2]];
}
p2 = 0;
while (p1 != p2) {
p1 = nums[p1];
p2 = nums[p2];
}
return p1;
}
};
总结
这道题难就难在要想到考的是带环的链表性质。我之前就没有接触过带环的链表,所以都是看了相关的介绍才知道正确的解题思路,今天学到了新的东西,感觉真棒~
拿下了今天首坑!明天继续加油!