这是我参与更文挑战的第3天,活动详情查看: 更文挑战
描述
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.
Note:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
解析
根据题意,就是给出了 arr ,按升序顺序找出不在 arr 中的第 k 个正整数。思路简单,先找出符合范围的所有整数集合 1 ~arr[-1]+k ,然后找到 arr 的集合,将两个集合做差找出不在 arr 中的数字集合,对其排序找到第 k 个数字即为答案。
解答
class Solution(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
a = set([i for i in range(1, arr[-1]+k+1)])
b = set(arr)
c = list(a-b)
return sorted(c)[k-1]
运行结果
Runtime: 44 ms, faster than 28.37% of Python online submissions for Kth Missing Positive Number.
Memory Usage: 13.8 MB, less than 9.59% of Python online submissions for Kth Missing Positive Number.
解析
还有一种思路是一种二分法的变种,结合下面的解答过程解释,missing 表示当前位置的数字前缺失的数字个数,如果缺失的数字小于 k ,说明还不能找到第 k 个缺失的数字,那么继续二分,如果缺失的数字个数大于等于 k ,说明可以找到第 k 个缺失的数字了,停止二分,最后的结果为 l+k ,表示当结果为 l+k 时,其前面缺失的正好是 k-1 个数字,l+k 本身正好是缺失的第 k 个数字 。解释的不清晰,看原作者的解释吧。汗颜。。。 leetcode.com/problems/kt…
解答
class Solution(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
l, r = 0, len(A)
while l < r:
m = (l + r) // 2
missing = A[m] - 1 - m
if missing < k:
l = m + 1
else:
r = m
return l + k
运行结果
Runtime: 28 ms, faster than 97.28% of Python online submissions for Kth Missing Positive Number.
Memory Usage: 13.7 MB, less than 9.59% of Python online submissions for Kth Missing Positive Number.
原题链接:leetcode.com/problems/kt…
您的支持是我最大的动力