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..10,, 小于等于5的一定有5个,如果多于5个,就在lower part, 等于5个就是upper part.
public class Solution {
public int findDuplicate(int[] nums) {
int low=1;
int high=nums.length-1;
int mid=0;
while(low<=high){
if(high==low) return high;
mid=low+(high-low)/2;
int temp=count(nums,mid);
if(temp>mid){
high=mid;
}else{
low=mid+1;
}
}
return -1;
}
int count(int[] nums,int key){
int res=0;
for(int i=0;i<nums.length;i++){
if(nums[i]<=key){
res++;
}
}
return res;
}
}
本文介绍了一种在不修改原始数组且仅使用常数级额外空间的情况下,寻找数组中唯一重复数字的方法。该方法利用二分查找原理,适用于包含n+1个整数的数组,每个整数范围在1到n之间。
3万+

被折叠的 条评论
为什么被折叠?



