Trie树

2935. 找出强数对的最大异或值 II - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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()

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

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

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
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:
root = Trie()
nums.sort()
n = len(nums)
ret = left = 0
for y in nums:
root.insert(y)
while nums[left] * 2 < y:
root.remove(nums[left])
left += 1
ret = max(ret, root.max_xor(y))
return ret

Trie树
https://brtulien.github.io/2023/11/16/Trie树/
作者
Brtulien
发布于
2023年11月16日
更新于
2024年7月1日
许可协议