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-n,以二分法开始,每次统计比mid小或等于其的元素个数,若其个数小于等于mid,则说明小于mid的部分不存在相同的元素,更新left。时间复杂度O(nlogn)
public class Solution {
public int findDuplicate(int[] nums) {
int n=nums.length;
int left=1;
int right=n-1;
int mid;
int left_num;
while(left<right){
mid=left+(right-left)/2;
left_num=0;
for(int i=0;i<n;i++){
if(nums[i]<=mid)
left_num++;
}
if(left_num<=mid)
left=mid+1;
else
right=mid;
}
return left;
}
}