41. First Missing Positive

这篇博客探讨了两种不同的算法实现,用于找到给定数组中缺失的第一个正整数。方法1简单地使用集合来查找,而方法2则通过调整数组元素位置进行标记。这两种方法都在解决空间复杂度和效率问题上有所不同。文章还提供了代码实现和运行时间分析。
摘要由CSDN通过智能技术生成

method 1:可以通过,但不满足空间O(1)

当s 不是集合无法通过。数字 i 一定在1到数组长度加1之间,比如nums = [1, 2, 3], 那么结果为4
nums = [1, 2, 2], 结果为 3
Runtime: 1346 ms, faster than 9.34% of Python3 online submissions for First Missing Positive.

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        s = set(nums)
        for i in range(1, len(nums) + 2):
            if i not in s:
                return i

method 2: 利用下标标记已经访问数字

1 检查是否有负数及0,如果有, 变为len(nums) + 1
2 把访问过的数字存在下标的位置上,用负数作标记
3 读取第一个正数或者利用长度+ 1

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        # keep all positive
        for idx in range(len(nums)):
            if nums[idx] <= 0 or nums[idx] > len(nums):
                nums[idx] = len(nums) + 1
        
        # placing marker
        for num in nums:
            num = abs(num) # avoid wrong doing of negative marking
            if num <= len(nums) and nums[num - 1] >= 0: # num <= len(nums), avoid index out of range
                nums[num - 1] *= -1
        # get res
        for idx in range(len(nums)):
            if nums[idx] > 0:
                return idx + 1
        return len(nums) + 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值