287. Find the Duplicate Number

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;
    }
   
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容