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