[leetcode] 1539. Kth Missing Positive Number

Description

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.

Constraints:

  • 1 <= arr.length <= 1000
  • 1 <= arr[i] <= 1000
  • 1 <= k <= 1000
  • arr[i] < arr[j] for 1 <= i < j <= arr.length

分析

题目的意思是:给你一个递增数组,找出第K个缺省的值。很直接,暴力破解就能够解决,如代码一,找到第K个就行了。我在看别人的解法的时候发现了一个更好的解法,只需要遍历arr数组就行了,每次遍历的时候计算两数之间缺省的值的个数,然后推算出第K个位置,很巧妙哈哈哈。

代码一

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        i=1
        j=0
        cnt=0
        n=len(arr)
        res=[]
        while(cnt<k):
            if(j<n and i<arr[j]):
                res.append(i)
                i+=1
                cnt+=1
            elif(j<n and i==arr[j]):
                j+=1
                i+=1
            elif(j>=n):
                res.append(i)
                i+=1
                cnt+=1
        return res[-1]

代码二

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        missing=0
        n=len(arr)
        for i in range(n):
            if(i==0):
                missing=arr[i]-1
            else:
                missing+=arr[i]-arr[i-1]-1
            if(missing>=k):
                return arr[i]-(missing-k)-1
        return arr[-1]+k-missing
            
        return res[-1]

参考文献

[LeetCode] Python, single array pass. Time: O(N), Space: O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值