[leetcode]287. Find the Duplicate Number

[leetcode]287. Find the Duplicate Number


Analysis

fighting!!!—— [每天刷题并不难0.0]

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.
在这里插入图片描述

Implement

(二分查找O(nlogn))

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83270126