Description: Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive.
There is only one repeated number in nums
, return this repeated number.
Link: 287. Find the Duplicate Number
Examples:
Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3 Example 3: Input: nums = [1,1] Output: 1 Example 4: Input: nums = [1,1,2] Output: 1
Follow up:
- How can we prove that at least one duplicate number must exist in
nums
? - Can you solve the problem without modifying the array
nums
? - Can you solve the problem using only constant,
O(1)
extra space? - Can you solve the problem with runtime complexity less than
O(n2)
?
思路: 我们可以return collections.Counter(nums).most_common(1)[0][0],或者类似的dict()计数,但是都不符合O(1)空间复杂度的要求,虽然时间是O(n). 不可以改变原nums.也就是不可以排序。所以按照题解的意思,所有的在nums中的数字都在区间[1,n]中,[1,n]共有n个unique numbers,如果一共有n+1个数,必然至少有一个数被重复了一次或者多次,题目中说,All the integers in nums
appear only once except for precisely one integer which appears two or more times.只有一个数字出现两次或者多次,我们二分查找区间[1,n],而不是nums.具体地,l=1,r=n, 求mid,然后数一下nums中小于等于mid的个数,如果多余mid个,说明被重复的数在[1,mid]之间,反之,[mid+1,r],注意结束条件是l < r,如果l<=r就会陷入死循环。时间复杂度是O(nlogn)
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ l, r = 1, len(nums)-1 while l < r: mid = int((l+r)/2) s = 0 for i in nums: if i <= mid: s += 1 if s > mid: r = mid else: l = mid+1 return l
看到还有O(n)时间复杂度的解法。
日期: 2021-04-14