【重点】【特例】41.缺失的第一个正数

文章介绍了两种方法解决LeetCode上的第一缺失正整数问题,一种是使用哈希表标记数组中存在的数字,另一种是遍历数组查找缺失的正整数。

题目

Python

最佳算法

class Solution:
    def firstMissingPositive(self, nums: list[int]) -> int:
        n = len(nums)
        for i in range(n):
            # 如果当前学生的学号在 [1,n] 中,但(真身)没有坐在正确的座位上
            while 1 <= nums[i] <= n and nums[i] != nums[nums[i] - 1]:
                # 那么就交换 nums[i] 和 nums[j],其中 j 是 i 的学号
                j = nums[i] - 1  # 减一是因为数组下标从 0 开始
                nums[i], nums[j] = nums[j], nums[i]

        # 找第一个学号与座位编号不匹配的学生
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1

        # 所有学生都坐在正确的座位上
        return n + 1

兜底做法

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

Java

法1:哈希表

实际上,对于一个长度为N的数组,其中没有出现的最小正整数只能在 [1, N + 1]中。这是因为如果[1, N] 都出现了,那么答案是 N + 1,否则答案是[1, N] 中没有出现的最小正整数。

class Solution {
    public int firstMissingPositive(int[] nums) {
        boolean[] array = new boolean[nums.length];
        Arrays.fill(array, false);
        for (int n : nums) {
            if (n > 0 && n <= nums.length) {
                array[n - 1] = true;
            }
        }
        for (int i = 0; i < array.length; ++i) {
            if (!array[i]) {
                return i + 1;
            }
        }

        return nums.length + 1;
    }
}

法2

其他方法参见:https://leetcode.cn/problems/first-missing-positive/solutions/304743/que-shi-de-di-yi-ge-zheng-shu-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值