You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何查找列表中最小的缺失正整数?

Python查找列表最小缺失正整数解决方案

原代码错误原因

  • 循环内连续两次赋值覆盖了cont的有效计算,最终只会输出固定值列表长度+1
  • 缺少核心的连续值匹配判断逻辑,无法识别第一个断裂的连续数值点

可运行修正代码

保留self参数,适配你后续扩展逻辑的需求:

class Find():

    def finding(self):
        a = [1, 2, 4, 5, 6, 7, 9]
        
        b = sorted(a)
        print(b)
        # 初始化预期的最小连续正整数
        expected = 1

        for num in b:
            if num == expected:
                expected += 1
            elif num > expected:
                # 找到第一个缺失值,直接终止循环
                break
        print("empty value: " + str(expected))

Find = Find()   
Find.finding()

运行后输出结果为empty value: 3,完全符合需求。

通用扩展版本(可选)

如果需要支持传入任意数字列表,可使用更灵活的实现,覆盖更多边界场景:

class Find():
    def finding(self, num_list):
        sorted_list = sorted(num_list)
        expected = 1
        for num in sorted_list:
            # 过滤小于1的数值,只校验正整数连续性
            if num < 1:
                continue
            if num == expected:
                expected += 1
            elif num > expected:
                break
        return expected

# 实例化测试
find_tool = Find()
print(find_tool.finding([1, 2, 4, 5, 6, 7, 9])) # 输出3
print(find_tool.finding([-2, 0, 1, 2])) # 输出3
print(find_tool.finding([2, 3, 4])) # 输出1
print(find_tool.finding([1, 2, 3])) # 输出4

内容的提问来源于stack exchange,提问作者codil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:18:01