287. 寻找重复数
题意:即nums长为n+1,里面的元素值范围:[1,n],有且仅有一个重复值,但该值可以重复多次,所以[1,n]有的数可以不在nums里。
方法一:二分查找。
class Solution(object):
# 二分查找
def findDuplicate(self, nums):
low = 1
high = len(nums) - 1
while low < high:
mid = low + int((high - low) / 2)
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
high = mid
else:
low = mid + 1
return low
方法二:双指针。
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
low, fast = 0, 1
while fast < len(nums):
if nums[low] != nums[fast]:
low += 1
fast += 1
else:
return nums[fast]