您的位置:首页 > 其它

Leetcode (287) Find the Duplicate Number

2016-09-23 23:17 274 查看
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.

题意:给定一个长度为n+1的整数序列,其中的数字全部都在1~n之间,且只有一个数字是出现了多遍,而其余的数字都是只出现过一遍的,要求找出那一个出现了多遍的数字。

要求:时间复杂度低于O(n2),空间复杂度为O(1),且不能够修改该整数序列。

思路:

空间复杂度要为O(1),即不能多开空间记录数字的出现次数,而位运算,异或运算又是用来计算得到唯一一个出现次数为奇数的数字,因此这些都不可行。

而因为对于数字1-n(中间可以缺少几个),若打乱它们的顺序,得到一个新的序列a[1…n],那么,a[i]=j表示数字i有一条与j相连的无向边,那么,就会注意到,其中有n个节点,一共n条边,即其中至少存在一个环。而显然,若有两个地方会入环,那么该处即为要求的重复的元素。

而现在有n+1个数字,即a[0…n],因为数列中的数字都是1-n的,所以不会有节点与0相连,所以从0开始就会有一条路径进入环。

因此,现在就有两个问题需要解决,一个是找到环,一个是找到环的入口。而注意到,要找到链表中的环,可以使用快慢指针来解决,时间复杂度是O(n),而找到重复的位置,则只需从0开始逐个检查即可。

为什么说第二阶段逐个检查即可呢?是因为目的是要找到进入环的位置,而快慢指针位移之差l=2l−l=(x+y+λ1c)−(x+y+λ2c)=n∗c,其中l为慢指针走过的长度,2l极为快指针的路程,x为0到环的开始的长度,y为相遇时与环开始的偏离长度,c为圈长度,可以得到l是圈长度的倍数,所以现在慢指针在差c−y到圈开始,0差x到圈开始,当0走到圈开始时,即有慢指针与圈开始的偏移量为y+x=l−λ1c,因为l为c的倍数,lambda也为整数,所以就是必然在开始处相遇。

python代码:

class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
fst, slw = 0, 0
slw = nums[slw]
fst = nums[nums[fst]]
while fst != slw:
slw = nums[slw]
fst = nums[nums[fst]]
fst = 0
while slw != fst:
slw = nums[slw]
fst = nums[fst]
return slw
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode