Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Trie:
- def __init__(self):
- self.val = None
- self.count = 0
- self.children = [None, None]
- def add(self, val, nbits):
- cur = self
- for cur_bit_idx in range(nbits - 1, -1, -1):
- cur_bit = 1 if (val & (1 << cur_bit_idx)) else 0
- if cur.children[cur_bit] is None:
- cur.children[cur_bit] = Trie()
- if cur_bit_idx == 0:
- cur.children[cur_bit].val = val
- cur.count += 1
- cur = cur.children[cur_bit]
- cur.count += 1
- def get_max(self, val, nbits):
- cur = self
- for cur_bit_idx in range(nbits - 1, -1, -1):
- cur_bit = 1 if (val & (1 << cur_bit_idx)) else 0
- non_cur_bit = 0 if cur_bit else 1
- bit_to_use = cur_bit
- if cur.children[non_cur_bit] and cur.children[non_cur_bit].count > 0:
- bit_to_use = non_cur_bit
- cur = cur.children[bit_to_use]
- return val ^ cur.val
- def repr(self):
- cs = []
- for c in self.children:
- if not c:
- cs.append(None)
- else:
- cs.append(c.repr())
- return (self.val, self.count, cs)
- class Solution:
- def findMaximumXOR(self, nums: List[int]) -> int:
- N = len(nums)
- nums.sort()
- if nums[-1] == 0:
- return 0
- nbits = nums[-1].bit_length()
- ans = 0
- trie = Trie()
- for i, n in enumerate(nums):
- if i > 0:
- ans = max(ans, trie.get_max(n, nbits))
- trie.add(n, nbits)
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement