题目截图
题目分析
排序后,限定了x和y的相对位置
假设y > x,随着y的移动,必须要保证2x >= y
所以可以使用滑动窗口维护一堆满足条件的x
这些x的异或值记录在Trie树中即可
ac code
class Node:
__slots__ = 'children', 'cnt'
def __init__(self):
self.children = [None, None]
self.cnt = 0 # 子树大小
class Trie:
HIGH_BIT = 19
def __init__(self):
self.root = Node()
# 添加 val
def insert(self, val: int) -> None:
cur = self.root
for i in range(Trie.HIGH_BIT, -1, -1):
bit = (val >> i) & 1
if cur.children[bit] is None:
cur.children[bit] = Node()
cur = cur.children[bit]
cur.cnt += 1 # 维护子树大小
return cur
# 删除 val,但不删除节点
# 要求 val 必须在 trie 中
def remove(self, val: int) -> None:
cur = self.root
for i in range(Trie.HIGH_BIT, -1, -1):
cur = cur.children[(val >> i) & 1]
cur.cnt -= 1 # 维护子树大小
return cur
# 返回 val 与 trie 中一个元素的最大异或和
# 要求 trie 中至少有一个元素
def max_xor(self, val: int) -> int:
cur = self.root
ans = 0
for i in range(Trie.HIGH_BIT, -1, -1):
bit = (val >> i) & 1
# 如果 cur.children[bit^1].cnt == 0,视作空节点
if cur.children[bit ^ 1] and cur.children[bit ^ 1].cnt:
ans |= 1 << i
bit ^= 1
cur = cur.children[bit]
return ans
class Solution:
def maximumStrongPairXor(self, nums: List[int]) -> int:
nums.sort()
t = Trie()
ans = left = 0
for y in nums:
t.insert(y)
# 只考虑nums[left] * 2 >= y,否则滑走
while nums[left] * 2 < y:
t.remove(nums[left])
left += 1
ans = max(ans, t.max_xor(y))
return ans
01Trie树模版
class Node:
__slots__ = 'children', 'cnt'
def __init__(self):
self.children = [None, None]
self.cnt = 0 # 子树大小
class Trie:
HIGH_BIT = 19
def __init__(self):
self.root = Node()
# 添加 val
def insert(self, val: int) -> None:
cur = self.root
for i in range(Trie.HIGH_BIT, -1, -1):
bit = (val >> i) & 1
if cur.children[bit] is None:
cur.children[bit] = Node()
cur = cur.children[bit]
cur.cnt += 1 # 维护子树大小
return cur
# 删除 val,但不删除节点
# 要求 val 必须在 trie 中
def remove(self, val: int) -> None:
cur = self.root
for i in range(Trie.HIGH_BIT, -1, -1):
cur = cur.children[(val >> i) & 1]
cur.cnt -= 1 # 维护子树大小
return cur
# 返回 val 与 trie 中一个元素的最大异或和
# 要求 trie 中至少有一个元素
def max_xor(self, val: int) -> int:
cur = self.root
ans = 0
for i in range(Trie.HIGH_BIT, -1, -1):
bit = (val >> i) & 1
# 如果 cur.children[bit^1].cnt == 0,视作空节点
if cur.children[bit ^ 1] and cur.children[bit ^ 1].cnt:
ans |= 1 << i
bit ^= 1
cur = cur.children[bit]
return ans
细节
__slot__加速