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.

二分,我們去統(tǒng)計數組中小于等于mid出現的個數,顯然,當出現的個數小于或者相等mid時,左側是合法的,重復出現在右半部分,當小于等于mid的數出現的次數大于mid的值時,說明重復出現在左半部分。
小于是可以出現的,只要這個數出現的次數足夠多,導致從1-mid的數中有至少一個數沒有出現。

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;
    }
   
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容