xinyu04

导航

LeetCode 1060 Missing Element in Sorted Array 二分

Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.

Solution

利用二分,我们每次二分的是右端点 \(m\) 满足:

\[a[m]-a[0]-m\ge k \]

这意味着缺失的数量足够 \(k\) 个,最后的答案就是 \(a[0]+l-1+k\)

点击查看代码
class Solution {

public:
    int missingElement(vector<int>& nums, int k) {
        int n = nums.size();
        int l=0, r=n;
        int mid=0;
        while(l<r){
            mid=(r-l)/2+l;
            if(nums[mid]-nums[0]-mid<k){
                // not enough missing value
                l=mid+1;
            }
            else r=mid;
        }
        return nums[0]+l-1+k;
    }
};

posted on 2022-09-14 22:13  Blackzxy  阅读(20)  评论(0编辑  收藏  举报