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:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

思路

明确题意,数组里的数是在1~(length-1)之间。而且重复次数可以是多次。 所以会有[1, 2, 4, 5, 7, 7, 7, 7, 8, 9]这种情况出现。最直接的方法就是用O(nlogn)的复杂度,对原数组进行排序,然后挨个比较一下就可以知道到底哪个数属于重复的了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
number = 0
nums.sort()
print nums
for i, num in enumerate(nums):
if (i < length - 1):
if (nums[i] == nums[i+1]):
number = nums[i]
break
return number

可以用快慢指针:

图解 https://discuss.leetcode.com/topic/25685/java-o-n-time-and-o-1-space-solution-similar-to-find-loop-in-linkedlist

还可以用二分法搜索:非常巧妙而常用的方法【之前出现过】

统计小于二分搜索到元素的数字的个数。如果这样的个数多于该数字,那肯定是有重复的元素的。