LeetCode 题解工作台
操作后的最大异或和
给你一个下标从 0 开始的整数数组 nums 。一次操作中,选择 任意 非负整数 x 和一个下标 i , 更新 nums[i] 为 nums[i] AND (nums[i] XOR x) 。 注意, AND 是逐位与运算, XOR 是逐位异或运算。 请你执行 任意次 更新操作,并返回 nums 中所…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
在一次操作中,我们可以把 更新为 $\textit{nums}[i] \text{ AND } (\textit{nums}[i] \text{ XOR } x)$。由于 是任意非负整数,因此 $\textit{nums}[i] \oplus x$ 的结果是一个任意值,再与 逐位与运算,可以把 的二进制表示中的若干位 变为 。 而题目中要获取的是 所有元素的最大逐位异或和,对于一个二进…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。一次操作中,选择 任意 非负整数 x 和一个下标 i ,更新 nums[i] 为 nums[i] AND (nums[i] XOR x) 。
注意,AND 是逐位与运算,XOR 是逐位异或运算。
请你执行 任意次 更新操作,并返回 nums 中所有元素 最大 逐位异或和。
示例 1:
输入:nums = [3,2,4,6] 输出:7 解释:选择 x = 4 和 i = 3 进行操作,num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2 。 现在,nums = [3, 2, 4, 2] 且所有元素逐位异或得到 3 XOR 2 XOR 4 XOR 2 = 7 。 可知 7 是能得到的最大逐位异或和。 注意,其他操作可能也能得到逐位异或和 7 。
示例 2:
输入:nums = [1,2,3,9,2] 输出:11 解释:执行 0 次操作。 所有元素的逐位异或和为 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11 。 可知 11 是能得到的最大逐位异或和。
提示:
1 <= nums.length <= 1050 <= nums[i] <= 108
解题思路
方法一:位运算
在一次操作中,我们可以把 更新为 。由于 是任意非负整数,因此 的结果是一个任意值,再与 逐位与运算,可以把 的二进制表示中的若干位 变为 。
而题目中要获取的是 所有元素的最大逐位异或和,对于一个二进制位,只要在 中存在一个元素对应的二进制位为 ,那么这个二进制位对于最大逐位异或和的贡献就是 。因此答案就是 中所有元素的逐位或运算的结果。
时间复杂度 ,其中 为 的长度。空间复杂度 。
class Solution:
def maximumXOR(self, nums: List[int]) -> int:
return reduce(or_, nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests understanding of bitwise operations.
- question_mark
Evaluates ability to optimize algorithms for bit manipulation.
- question_mark
Assesses knowledge of iterative optimization techniques.
常见陷阱
外企场景- error
Failing to consider all possible values for x, limiting potential XOR results.
- error
Not optimizing the algorithm for large input sizes, leading to inefficiency.
- error
Misunderstanding the impact of applying multiple XOR operations on a single element.
进阶变体
外企场景- arrow_right_alt
Limit the number of allowed operations and evaluate the effect on XOR.
- arrow_right_alt
Introduce constraints on the values of x and explore its effect on the result.
- arrow_right_alt
Test with large input arrays and optimize for both time and space complexity.