用 Python 编写程序,查找从 1 到 N 的所有缺失数字
pythonserver side programmingprogramming更新于 2026/1/11 2:20:17
假设我们有一个数字列表,称为 nums,大小为 n,列表中的所有数字都存在于区间 [1, n] 中,有些元素可能出现两次,而其他元素只出现一次。我们必须从 [1, n] 中找到所有不在列表中的数字。我们必须返回按升序排序的数字。我们必须尝试找到一个需要线性时间和恒定空间的解决方案。
因此,如果输入为 [4, 4, 2, 2, 6, 6],则输出将为 [1, 3, 5]。
为了解决这个问题,我们将遵循以下步骤 −
- arr := 大小为 nums + 1 的数组,并用 0 填充
- 对于 nums 中的每个 i,执行
- arr[i] := arr[i] + 1
- missing := 一个新列表
- 对于范围为 0 到 arr 大小的 i,执行
- 如果 arr[i] 与 0 相同且 i 与 0 不同,则
- 插入i 位于 missing 的末尾
- 如果 arr[i] 与 0 相同且 i 与 0 不同,则
- 返回 missing
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): arr = [0]*(len(nums)+1) for i in nums: arr[i] += 1 missing = [] for i in range(len(arr)): if arr[i] == 0 and i != 0: missing.append(i) return missing ob = Solution() print(ob.solve([4, 4, 2, 2, 6, 6]))
输入
[4, 4, 2, 2, 6, 6]
输出
[1, 3, 5]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

