287 Find the Duplicate Number
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.
思路
明确题意,数组里的数是在1~(length-1)之间。而且重复次数可以是多次。 所以会有[1, 2, 4, 5, 7, 7, 7, 7, 8, 9]这种情况出现。最直接的方法就是用O(nlogn)的复杂度,对原数组进行排序,然后挨个比较一下就可以知道到底哪个数属于重复的了。
|
|
可以用快慢指针:
还可以用二分法搜索:非常巧妙而常用的方法【之前出现过】
统计小于二分搜索到元素的数字的个数。如果这样的个数多于该数字,那肯定是有重复的元素的。