在一个长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。
思路:因为长度为n+1,那么必然至少有一个重复数字,可利用类似二分查找,将范围定位为1~n/2,然后采取计数方式,如果整个数组在该范围的元素个数大于n/2,则1~n/2中存在重复数字(因为若按正常无重复数组来说个数肯定是n/2),若没有则重复数字在后半段即:n/2+1~n范围内。以此类推,直到定位到重复数字。
public int duplication(int numbers[],int length){
if(numbers==null||length<=0){
return -1; // -1代表不存在;
}
int l = 1;
int h = length -1;
int mid;
while(l<=h){
mid = (l+h)/2;
int numCount = getCount(number,l,mid);
if(l==h){
if(numCount>0){ // 找到相等元素
return l;
}else{ // 检测到最后亦然没检测到相等元素
return -1;
}
}
if(numberCount>mid-l+1){ //调整区间,对下一轮赋值
h = mid;
}else{
l = mid+1;
}
}
return -1;
}
public int getCount(int number,int l,int h){
if(number==null){
return 0;
}
int count;
for(number in numbers){
if(number<=h&&number>=l){
count++;
}
}
return count;
}
时间复杂度:O(nlogn)
空间复杂度:O(1)