LeetCode 题解工作台
数组中两个数的最大异或值
给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j 。 示例 1: 输入: nums = [3,10,5,25,2,8] 输出: 28 解释: 最大运算结果是 5 XOR 25 = 28. 示例 2: 输入: nums = [14,7…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
题目是求两个元素的异或最大值,可以从最高位开始考虑。 我们把数组中的每个元素 看作一个 位的 串,按二进制从高位到低位的顺序,插入前缀树(最低位为叶子节点)。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j < n 。
示例 1:
输入:nums = [3,10,5,25,2,8] 输出:28 解释:最大运算结果是 5 XOR 25 = 28.
示例 2:
输入:nums = [14,70,53,83,49,91,36,80,92,51,66,70] 输出:127
提示:
1 <= nums.length <= 2 * 1050 <= nums[i] <= 231 - 1
解题思路
方法一:前缀树
题目是求两个元素的异或最大值,可以从最高位开始考虑。
我们把数组中的每个元素 看作一个 位的 串,按二进制从高位到低位的顺序,插入前缀树(最低位为叶子节点)。
搜索 时,尽量走相反的 字符指针的策略,因为异或运算的法则是相同得 ,不同得 ,所以我们尽可能往与 当前位相反的字符方向走,才能得到能和 产生最大异或值的结果。
时间复杂度 ,空间复杂度 ,其中 是数组 的长度,而 是数组中元素的最大值。
class Trie:
__slots__ = ("children",)
def __init__(self):
self.children: List[Trie | None] = [None, None]
def insert(self, x: int):
node = self
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
def search(self, x: int) -> int:
node = self
ans = 0
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v ^ 1]:
ans |= 1 << i
node = node.children[v ^ 1]
else:
node = node.children[v]
return ans
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
trie = Trie()
for x in nums:
trie.insert(x)
return max(trie.search(x) for x in nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate can demonstrate knowledge of bitwise operations and their applications in optimization problems.
- question_mark
Candidate shows ability to use a trie structure for efficient lookups and optimizations.
- question_mark
Candidate understands the trade-offs between different approaches in terms of time and space complexity.
常见陷阱
外企场景- error
Not considering the importance of bit-level operations, which can lead to inefficient brute force solutions.
- error
Failing to optimize the space complexity when using a hash set or trie to store intermediate results.
- error
Overlooking edge cases, such as arrays with only one element or arrays containing only the same number.
进阶变体
外企场景- arrow_right_alt
Solving the problem without using a trie, relying solely on hash-based solutions.
- arrow_right_alt
Modifying the problem to consider an array of very large numbers, affecting time complexity.
- arrow_right_alt
Finding the maximum XOR value for subarrays instead of the entire array.