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èi)ソy(tǒng)計(jì)數(shù)組中小于等于mid出現(xiàn)的個(gè)數(shù),顯然,當(dāng)出現(xiàn)的個(gè)數(shù)小于或者相等mid時(shí),左側(cè)是合法的,重復(fù)出現(xiàn)在右半部分,當(dāng)小于等于mid的數(shù)出現(xiàn)的次數(shù)大于mid的值時(shí),說(shuō)明重復(fù)出現(xiàn)在左半部分。
小于是可以出現(xiàn)的,只要這個(gè)數(shù)出現(xiàn)的次數(shù)足夠多,導(dǎo)致從1-mid的數(shù)中有至少一個(gè)數(shù)沒有出現(xiàn)。
class Solution {
public int findDuplicate(int[] nums) {
int lo = 1 ;
int hi = nums.length-1;
int count = 0;
int pos =0;
while(lo<=hi)
{
count=0;
int mid = lo+(hi-lo)/2;
for(int i = 0 ;i<nums.length;i++)
{
if(nums[i]<=mid)
count++;
}
// <= when contains no duplicate ;
// > when contains duplicate ;
if(count<=mid)
lo=mid+1;
else if(count>mid)
{
hi=mid-1;
}
}
return lo;
}
}