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.
Basic Idea:
因为不能改变原来数组,而且空间复杂度要求是O(1),所以我们不能排序。
思路1:Binary Search 从 p = 0, r = n 开始,每次计算小于等于 mid 的数的个数,如果大于mid,则说明重复在左侧,否则在右侧。时间复杂度为 O(nlogn);
# binary search solution O(nlogn) timeclassSolution(object):deffindDuplicate(self,nums):""" :type nums: List[int] :rtype: int""" p =1 r =len(nums)-1while p +1< r: q =(r - p)/2+ p count =len([n for n in nums if n <= q])if count <= q: p = qelse: r = qiflen([n for n in nums if n <= p])> p:return pelse:return r
public class Solution {
public int findDuplicate(int[] nums) {
int slow = nums[0];
int fast = nums[nums[0]];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
int ret = 0;
while (ret != slow) {
slow = nums[slow];
ret = nums[ret];
}
return ret;
}
}