LeetCode 题解工作台
求出出现两次数字的 XOR 值
给你一个数组 nums ,数组中的数字 要么 出现一次, 要么 出现两次。 请你返回数组中所有出现两次数字的按位 XOR 值,如果没有数字出现过两次,返回 0 。 示例 1: 输入: nums = [1,2,1,3] 输出: 1 解释: nums 中唯一出现过两次的数字是 1 。 示例 2: 输入:…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们定义一个数组或哈希表 记录每个数字出现的次数。 接下来,遍历数组 ,当某个数字出现两次时,我们将其与答案进行异或运算。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个数组 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 <= 501 <= nums[i] <= 50nums中每个数字要么出现过一次,要么出现过两次。
解题思路
方法一:计数
我们定义一个数组或哈希表 记录每个数字出现的次数。
接下来,遍历数组 ,当某个数字出现两次时,我们将其与答案进行异或运算。
最后返回答案即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 是数组 中的最大值或数组 不同数字的个数。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.