首页 > 编程语言 > 详细

421. Maximum XOR of Two Numbers in an Array 数组中两个数的最大异或

时间:2018-01-23 00:26:02      阅读:275      评论:0      收藏:0      [点我收藏+]

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.

  1. class Solution:
  2. def findMaximumXOR(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: int
  6. """
  7. head = self.buildTrie(nums)
  8. maxXor = 0
  9. for num in nums:
  10. node = head
  11. curXor = 0
  12. for bit in range(31, -1, -1):
  13. chd = int(bool(num & (1 << bit)))
  14. if node[1 ^ chd]:
  15. curXor |= 1 << bit
  16. node = node[1 ^ chd]
  17. else:
  18. node = node[chd]
  19. maxXor = max(maxXor, curXor)
  20. return maxXor
  21. def buildTrie(self, nums):
  22. root = [None, None]
  23. for num in nums:
  24. cur = ‘{0:b}‘.format(num).zfill(32)
  25. node = root
  26. for i in cur:
  27. bit = int(i)
  28. if not node[bit]:
  29. node[bit] = [None, None]
  30. node = node[bit]
  31. return root
  32. nums = [3, 10, 5, 25, 2, 8]
  33. s = Solution()
  34. res = s.findMaximumXOR(nums)
  35. print(res)





421. Maximum XOR of Two Numbers in an Array 数组中两个数的最大异或

原文:https://www.cnblogs.com/xiejunzhao/p/8331683.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!