用 Python 编写程序,查找数组中缺失的最小整数
pythonserver side programmingprogramming更新于 2026/1/14 22:36:17
假设我们有一个名为 nums 的数字列表,我们必须找到第一个缺失的正数。换句话说,就是数组中不存在的最小正数。数组也可以包含重复项和负数。
因此,如果输入为 nums = [0,3,1],则输出为 2
为了解决这个问题,我们将遵循以下步骤 −
nums := 一个包含 nums 中所有正数的集合
如果 nums 为空,则
返回 1
对于 i,范围从 1 到 nums 的大小 + 2,执行
如果 i 不存在于 nums 中,则
返回 i
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): nums = set(num for num in nums if num > 0) if not nums: return 1 for i in range(1, len(nums) + 2): if i not in nums: return i ob = Solution() nums = [0,3,1] print(ob.solve(nums))
输入
[0,3,1]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

