Advertisement
kosievdmerwe

Untitled

Jan 26th, 2022
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. class Trie:
  2.     def __init__(self):
  3.         self.val = None
  4.         self.count = 0
  5.         self.children = [None, None]
  6.    
  7.     def add(self, val, nbits):
  8.         cur = self
  9.         for cur_bit_idx in range(nbits - 1, -1, -1):
  10.             cur_bit = 1 if (val & (1 << cur_bit_idx)) else 0
  11.             if cur.children[cur_bit] is None:
  12.                 cur.children[cur_bit] = Trie()
  13.        
  14.             if cur_bit_idx == 0:
  15.                 cur.children[cur_bit].val = val
  16.                
  17.             cur.count += 1
  18.             cur = cur.children[cur_bit]
  19.         cur.count += 1
  20.            
  21.     def get_max(self, val, nbits):
  22.         cur = self
  23.         for cur_bit_idx in range(nbits - 1, -1, -1):
  24.             cur_bit = 1 if (val & (1 << cur_bit_idx)) else 0
  25.             non_cur_bit = 0 if cur_bit else 1
  26.        
  27.             bit_to_use = cur_bit
  28.             if cur.children[non_cur_bit] and cur.children[non_cur_bit].count > 0:
  29.                 bit_to_use = non_cur_bit
  30.             cur = cur.children[bit_to_use]
  31.         return val ^ cur.val
  32.            
  33.        
  34.     def repr(self):
  35.         cs = []
  36.         for c in self.children:
  37.             if not c:
  38.                 cs.append(None)
  39.             else:
  40.                 cs.append(c.repr())
  41.         return (self.val, self.count, cs)
  42.  
  43.  
  44. class Solution:
  45.     def findMaximumXOR(self, nums: List[int]) -> int:
  46.         N = len(nums)
  47.  
  48.         nums.sort()
  49.         if nums[-1] == 0:
  50.             return 0
  51.        
  52.         nbits = nums[-1].bit_length()
  53.        
  54.         ans = 0
  55.         trie = Trie()
  56.         for i, n in enumerate(nums):
  57.             if i > 0:
  58.                 ans = max(ans, trie.get_max(n, nbits))
  59.             trie.add(n, nbits)
  60.         return ans
  61.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement