1539. Kth Missing Positive Number

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

Find the kth positive integer that is missing from this array.

Example 1:

Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.

Example 2:

Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
class Solution(object):
    def findKthPositive(self, arr, k):
        """
        :type arr: List[int]
        :type k: int
        :rtype: int
        """
        #对于每个元素ai,我们都可以唯一确定到第i个元素为止缺失的元素数量为ai - i - 1
        #二分查找,只要找到一个i使得p(i-1) < k < pi
        #就可以确定缺失的第k个数为k - p(i-1) + a(i-1)
        #也就是我们要找到第一个大于等于k的pi
        if arr[0] > k:
            return k
        l,r = 0, len(arr)
        while l < r:
            mid = (l + r)//2
            # arr[mid] - mid - 1 缺失的元素数量,缺失元素在右半边
            if arr[mid] - mid - 1 < k:
                l = mid + 1
            else:
                r = mid
        return r + k
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值