题目:Find the Duplicate Number My Submissions QuestionEditorial Solution
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.
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.
先说一个定理:n + 1个整数, 都在(1 , n)区间,肯定有重复的数,。
意思是说,给你一组数n + 1 个整数,在1,和n之间。肯定有重复的数,让你找出重复的数,只有一个重复的数,但这个数可以重复好几次。
有3个要求:
1.不能改变数组
2.O(1)的空间复杂度,
3.小于
O(n2)
的时间复杂度
刚开始想就排序一下,符合3但是不能同时符合条件1和2
暴力遍历两次,也不行,不符合3
想到的办法就是二分法,
具体怎么做呢,举个例子
[2,4,5,6,1,3,5,8,7,9]
先看一半,[1,5]的数,一共有6个,[6,9]数一共有4个。
说明肯定重复的数肯定在[1,5]里,
下面只看[1,5]的数,在[1,3]区间里的数里有3个,在[4,5]区间里的数有3个,那么肯定重复的数在[4,5]区间里。
最后一轮等于4的数只有一个,等于5的数有两个。所以最终重复的数是5.
下面是代码:
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.pruneNums(nums,1, len(nums)-1)
def pruneNums(self, nums, left, right):
if left == right:
return left
mid = (left + right)/2
lidx = 0
ridx = 0
for i in nums:
if i <= mid :
lidx += 1
else:
ridx += 1
if lidx > mid:
return self.pruneNums(nums,left, mid)
else:
return self.pruneNums(nums,mid + 1, right)