image.png

思路:字典树 + 贪心

  • 首先建立一棵字典树,高位的节点应该放在离根近的地方,所有的数字都挂在了树上
  • 从根节点往下读,选择一个当前的数字num,如果num最高位是1,那么就往0的方向去走。尽可能保证高位的结果是1,读完整棵树就可以了
  • 需要注意的是,如何将一个32位的整数,将最左边标为0号,最右边标为31号(从左向右,从0到31标号),(num >> (31 - i)) & 1

image.png

代码:

  1. class TrieNode:
  2. def __init__(self):
  3. self.children = [None for i in range(2)]
  4. def insertNum(self, nums: List[int]) -> None:
  5. for num in nums:
  6. curNode = self
  7. for i in range(1, 32):
  8. curBit = ((num >> (31 - i)) & 1)
  9. if curNode.children[curBit] == None:
  10. curNode.children[curBit] = TrieNode()
  11. curNode = curNode.children[curBit]
  12. class Solution:
  13. # 所谓最大值,本质上就是希望两个数字各自能提供尽可能多的'1'
  14. # 先建一棵树,可以全挂上去(这一步应该有优化,但是我没有想到)
  15. def traverseTrie(self, node: TrieNode, num: int) -> None:
  16. maxRes = 0
  17. for i in range(1, 32):
  18. curBit = (num >> (31 - i)) & 1
  19. chooseDirection = curBit ^ 1
  20. if node.children[chooseDirection] != None:
  21. node = node.children[chooseDirection]
  22. maxRes += (1 <<(31 - i))
  23. else:
  24. node = node.children[curBit]
  25. return maxRes
  26. def findMaximumXOR(self, nums: List[int]) -> int:
  27. trieRoot = TrieNode()
  28. trieRoot.insertNum(nums)
  29. maxRes = 0
  30. for num in nums:
  31. maxRes = max(maxRes, self.traverseTrie(trieRoot, num))
  32. return maxRes