Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.
class Solution:def findMaximumXOR(self, nums):""":type nums: List[int]:rtype: int"""head = self.buildTrie(nums)maxXor = 0for num in nums:node = headcurXor = 0for bit in range(31, -1, -1):chd = int(bool(num & (1 << bit)))if node[1 ^ chd]:curXor |= 1 << bitnode = node[1 ^ chd]else:node = node[chd]maxXor = max(maxXor, curXor)return maxXordef buildTrie(self, nums):root = [None, None]for num in nums:cur = ‘{0:b}‘.format(num).zfill(32)node = rootfor i in cur:bit = int(i)if not node[bit]:node[bit] = [None, None]node = node[bit]return rootnums = [3, 10, 5, 25, 2, 8]s = Solution()res = s.findMaximumXOR(nums)print(res)