题目:
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.
class Solution {
public int findDuplicate(int[] nums) {
//给定1-n的数组,其中只有一个数重复多次,找出该数
//要求:不能修改该数组,空间复杂度O(1),时间复杂度少于O(n^2)
//思路: 采用二分查找,对前半部分和后半部分分别统计各数字出现的次数,如果该数字出现大于1,则说明为重复数字
int low=1,high=nums.length-1;
while(low<=high){
//取中数
int mid=low+(high-low)/2;
//统计属于该阶段的数有多少个
int count=countRange(nums,low,mid);
if(low==high){
//已经到中间
if(count>1){
//返回该数据
return low;
}else{
break;
}
}
if(count>(mid-low+1)){
//说明前半部分存在重复
high=mid;
}else{
//后半部分存在重复
low=mid+1;
}
}
return -1;
}
//统计出现次数
public int countRange(int[] nums,int start,int end){
if(nums.length==0||nums==null) return 0;
int count=0;
for(int i=0;i<nums.length;i++){
if(nums[i]>=start&&nums[i]<=end){
count++;
}
}
return count;
}
}