力扣 287. 寻找重复数

二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def findDuplicate(nums):
# 二分查找
left, right = 1, len(nums) - 1
while left < right:
mid = (left + right) >> 1
count = 0
for n in nums:
if n <= mid:
count += 1
if count <= mid:
left = mid + 1
else:
right = mid

return left

双指针

1
2
3
4
5
6
7
8
9
10
11
def findDuplicate(nums):
# 双指针
low, fast = nums[0], nums[nums[0]]
while low != fast:
low = nums[low]
fast = nums[nums[fast]]
fast = 0
while low != fast:
low = nums[low]
fast = nums[fast]
return fast
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信