题目描述
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-duplicate-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
这一题有两个解法都是是很奇妙
链表环 快慢指针
class Solution(object):
def findDuplicate(self, nums):
# The "tortoise and hare" step. We start at the end of the array and try
# to find an intersection point in the cycle.
slow = 0
fast = 0
# Keep advancing 'slow' by one step and 'fast' by two steps until they
# meet inside the loop. they may step i loops,slow step n steps ,fast step 2*n ,each loop have n/i steps
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# Start up another pointer from the end of the array and march it forward
# until it hits the pointer inside the array.
finder = 0
while True:
slow = nums[slow]
finder = nums[finder]
# If the two hit, the intersection index is the duplicate element.
if slow == finder:
return slow
作者:Damien_Undo
链接:https://leetcode-cn.com/problems/two-sum/solution/kuai-man-zhi-zhen-yuan-li-jian-yi-jie-shi-by-damie/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
二分查找
关键是对数得范围二分,而不是对数组得索引二分。
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
left = 1
right = len(nums)-1
while left < right :
mid = left+ (right -left) //2
count = 0
for i in range(len(nums)):
if nums[i] <= mid:
count +=1
if count > mid :
right = mid
else:
left = mid +1
return left