leetcode-41. 缺失的第一个正数

题目

给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。

示例 1:

输入: [1,2,0]
输出: 3

示例 2:

输入: [3,4,-1,1]
输出: 2

示例 3:

输入: [7,8,9,11,12]
输出: 1

解题思路

Use number value as the index, find a way to label those appeared numbers.

Because we want to find the first positive number, and if all of the positive appeared, then the nums would be in the range: [1, n].
We can delete those numbers out of this range first, by making them 0s. Then go through the list, if the number is in this range, then the new index would be: val - 1. Use this index to change the number. We use add n + 1 here, we can’t use * -1 here because we change the numbers to 0 when we deleting them. If the index is called, and the value is 0, we can’t tell if the index is called or not by the final result.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

代码

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        # delete other numbers
        for i in range(len(nums)):
            if nums[i] <= 0 or nums[i] > n:
                nums[i] = 0
        # transform all the numbers
        for each_num in nums:
            each_num %= (n + 1)
            if 1 <= each_num <= n:
                index = each_num - 1
                nums[index] += n + 1
        # check the final results
        for i in range(len(nums)):
            if nums[i] < n + 1:
                return i + 1
        return n + 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值