这道题最简单的方式是用二分搜索。首先设置head, tail指针分别指向1和n,head <= duplicate number <= tail。计算mid = (tail + head)/2,遍历数组查找<=mid的数的个数。如果大于mid个,说明重复元素在[head, mid]之间,更新tail = mid;否则说明重复元素在[mid + 1, tail]之间,更新head = mid + 1。
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 答案在[low, high]之间
low = 1
high = len(nums) - 1
while low < high:
mid = (low + high) // 2
# 计算[low, mid]之间个数
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
# case 1: 答案在[low, mid]之间
high = mid
else:
# case 2: 答案在[mid + 1, high]之间
low = mid + 1
return low