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.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2] Output: 3
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.
思路:
1. 如果有duplicate,一定有环,而且重复的数就在环人口
2、 二分:At first the search space is numbers between 1 to n. Each time I select a number mid (which is the one in the middle) and count all the numbers equal to or less than mid. Then if the count is more than mid, the search space will be [1 mid] otherwise [mid+1 n]. I do this until search space is only one number.
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return -1
slow, fast = nums[0], nums[nums[0]]
while slow!=fast:
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while fast!=slow:
slow = nums[slow]
fast = nums[fast]
return slow
s=Solution()
print(s.findDuplicate([1,3,4,2,2]))
print(s.findDuplicate([3,1,3,4,2]))class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low = 1
high = len(nums)-1
while low < high:
mid = low+(high-low)/2
count = 0
for i in nums:
if i <= mid:
count+=1
if count <= mid:
low = mid+1
else:
high = mid
return low

本文介绍了一种在不修改原始数组且使用常数级额外空间的情况下查找数组中重复元素的方法。通过利用快慢指针定位环入口及二分查找缩小搜索范围,实现高效查找重复值。

222

被折叠的 条评论
为什么被折叠?



