LeetCode 题解工作台

丢失的数字

给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。 示例 1: 输入: nums = [3,0,1] 输出: 2 解释: n = 3 ,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 n…

category

6

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

异或运算的性质: - 任何数和 做异或运算,结果仍然是原来的数,即 $x \oplus 0 = x$;

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。

 

示例 1:

输入:nums = [3,0,1]

输出:2

解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。

示例 2:

输入:nums = [0,1]

输出:2

解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。

示例 3:

输入:nums = [9,6,4,2,3,5,7,0,1]

输出:8

解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。

提示:

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • nums 中的所有数字都 独一无二

 

进阶:你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?

lightbulb

解题思路

方法一:位运算

异或运算的性质:

  • 任何数和 00 做异或运算,结果仍然是原来的数,即 x0=xx \oplus 0 = x
  • 任何数和其自身做异或运算,结果是 00,即 xx=0x \oplus x = 0

因此,我们可以遍历数组,将数字 [0,..n][0,..n] 与数组中的元素进行异或运算,最后的结果就是缺失的数字。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组长度。

1
2
3
4
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        return reduce(xor, (i ^ v for i, v in enumerate(nums, 1)))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate’s ability to use a mathematical formula or XOR manipulation for efficiency.

  • question_mark

    Observe the clarity in how the candidate justifies the choice of approach for handling time and space constraints.

  • question_mark

    Check for an understanding of array scanning and hash table concepts, especially for large inputs.

warning

常见陷阱

外企场景
  • error

    Mistaking the problem for a simple search rather than recognizing the need for a missing number in the full range.

  • error

    Choosing an approach with excessive space complexity when an O(1) space solution is possible.

  • error

    Failing to handle edge cases like when n is 1, leading to incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow duplicates in the array, or change the range from [0, n] to [1, n].

  • arrow_right_alt

    Handle a missing number in an array containing negative numbers in the range.

  • arrow_right_alt

    Modify the input array to become unsorted, forcing the candidate to consider sorting or hash-based solutions.

help

常见问题

外企场景

丢失的数字题解:数组·哈希·扫描 | LeetCode #268 简单