LeetCode 题解工作台

错误的集合

集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。 给定一个数组 nums 代表了该集合发生错误后的结果。 请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 示例…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们用 表示 所有数字的和,用 表示数组 去重后的数字和,用 表示数组 的数字和。 那么 $s - s_2$ 就是重复的数字,而 $s_1 - s_2$ 就是缺失的数字。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复

给定一个数组 nums 代表了该集合发生错误后的结果。

请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

 

示例 1:

输入:nums = [1,2,2,4]
输出:[2,3]

示例 2:

输入:nums = [1,1]
输出:[1,2]

 

提示:

  • 2 <= nums.length <= 104
  • 1 <= nums[i] <= 104
lightbulb

解题思路

方法一:数学

我们用 s1s_1 表示 [1,..n][1,..n] 所有数字的和,用 s2s_2 表示数组 numsnums 去重后的数字和,用 ss 表示数组 numsnums 的数字和。

那么 ss2s - s_2 就是重复的数字,而 s1s2s_1 - s_2 就是缺失的数字。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n),其中 nn 是数组 numsnums 的长度。需要额外的空间对数组去重。

1
2
3
4
5
6
7
8
class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        n = len(nums)
        s1 = (1 + n) * n // 2
        s2 = sum(set(nums))
        s = sum(nums)
        return [s - s2, s1 - s2]
speed

复杂度分析

指标
时间complexity is O(n) because each element is scanned once or a constant number of times. Space complexity is O(n) if using a hash set, but can be reduced to O(1) with the bit manipulation or sum difference methods.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect an initial check for duplicates during array traversal.

  • question_mark

    Look for use of hash set or in-place marking to detect repeated numbers.

  • question_mark

    Confirm candidate recognizes missing number derivation using sum or XOR differences.

warning

常见陷阱

外企场景
  • error

    Overlooking that the array may not be sorted and assuming sequential indices.

  • error

    Double-counting elements or miscalculating the missing number after finding the duplicate.

  • error

    Using inefficient nested loops instead of O(n) scanning and hash tracking.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The array could contain multiple duplicates with multiple missing numbers, requiring generalized mapping.

  • arrow_right_alt

    Input array might be read-only, pushing the solution toward XOR or arithmetic methods.

  • arrow_right_alt

    Numbers could span a larger range with gaps, emphasizing the need for scalable hash-based scanning.

help

常见问题

外企场景

错误的集合题解:数组·哈希·扫描 | LeetCode #645 简单