【leetcode】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.


思路:
二分法。抄的作業,看的博文https://www.cnblogs.com/grandyang/p/4843654.html

全面剖析二分搜索算法:https://blog.csdn.net/zxc120389574/article/details/105714573


代碼實現:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int left = 1;
        int right = nums.size();
        int mid;
        
        while (left < right){
            mid = left + (right - left) / 2;
            
            int cnt = 0;
            for (int i = 0; i < nums.size(); ++i){
                if (nums[i] <= mid){
                    ++cnt;
                }
            }
            if (cnt <= mid){
                left = mid+1;
            }else{
                right = mid;
            }
        }
        return left;
    }
};

參考:
https://www.cnblogs.com/grandyang/p/4843654.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章