LeetCode 题解工作台

求出出现两次数字的 XOR 值

给你一个数组 nums ,数组中的数字 要么 出现一次, 要么 出现两次。 请你返回数组中所有出现两次数字的按位 XOR 值,如果没有数字出现过两次,返回 0 。 示例 1: 输入: nums = [1,2,1,3] 输出: 1 解释: nums 中唯一出现过两次的数字是 1 。 示例 2: 输入:…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们定义一个数组或哈希表 记录每个数字出现的次数。 接下来,遍历数组 ,当某个数字出现两次时,我们将其与答案进行异或运算。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数组 nums ,数组中的数字 要么 出现一次,要么 出现两次。

请你返回数组中所有出现两次数字的按位 XOR 值,如果没有数字出现过两次,返回 0 。

 

示例 1:

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

输出:1

解释:

nums 中唯一出现过两次的数字是 1 。

示例 2:

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

输出:0

解释:

nums 中没有数字出现两次。

示例 3:

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

输出:3

解释:

数字 1 和 2 出现过两次。1 XOR 2 == 3 。

 

提示:

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 50
  • nums 中每个数字要么出现过一次,要么出现过两次。
lightbulb

解题思路

方法一:计数

我们定义一个数组或哈希表 cnt\textit{cnt} 记录每个数字出现的次数。

接下来,遍历数组 nums\textit{nums},当某个数字出现两次时,我们将其与答案进行异或运算。

最后返回答案即可。

时间复杂度 O(n)O(n),空间复杂度 O(M)O(M)。其中 nn 是数组 nums\textit{nums} 的长度,而 MM 是数组 nums\textit{nums} 中的最大值或数组 nums\textit{nums} 不同数字的个数。

1
2
3
4
5
class Solution:
    def duplicateNumbersXOR(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return reduce(xor, [x for x, v in cnt.items() if v == 2], 0)
speed

复杂度分析

指标
时间complexity is O(n) due to single array scan. Space complexity is O(n) for the hash set storing seen numbers. Small array constraints make this approach efficient.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check whether the candidate uses extra space versus in-place tracking for duplicates.

  • question_mark

    Observe if XOR is applied only to numbers appearing twice, not all numbers.

  • question_mark

    Notice attention to edge cases where no number repeats or the array length is minimal.

warning

常见陷阱

外企场景
  • error

    XORing numbers that appear only once, which leads to incorrect results.

  • error

    Missing edge cases where no number appears twice, forgetting to return 0.

  • error

    Using nested loops instead of hash lookup, increasing time complexity unnecessarily.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the XOR of numbers appearing exactly three times instead of twice.

  • arrow_right_alt

    Find the XOR of all numbers appearing an odd number of times in the array.

  • arrow_right_alt

    Implement the solution without using extra space by modifying the array in-place.

help

常见问题

外企场景

求出出现两次数字的 XOR 值题解:数组·哈希·扫描 | LeetCode #3158 简单