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.
数组中有n+1个数,范围为1~n,请证明至少存在一个重复的数字。假设只有一个重复的数,请找出这个数。
假设n=4,那么数组中应该有5个数,每个数的范围为1~4且只有一个重复的数字。数组在放完1 2 3 4 后,如果在放一个数字的话必然会产生重复,目的就是找出这个重复的数字。
要求:
不要更改数组(限制你不要排序)
不要使用额外的空间(不要创建新的数组)
时间复杂度小于O(n
2
)
思路:
利用二分的思想。初始化一个mid值,如果数组中小于等于mid的值的个数小于等于mid这个值,那么可以说明重复数字在mid的右面,反之说明重复数字在mid值的左面。
public class Solution {
public int findDuplicate(int[] nums) {
int n=nums.length-1;
int low=1,high=n;
int mid=0;
//int count2=0;
while(low<high){
int count=0;
mid=(low+high)/2;
for(int i=0;i<nums.length;i++){
if(nums[i]<=mid)count++;
}
if(count<=mid) low=mid+1;
else high=mid;
}
return low;
}
}