zoukankan      html  css  js  c++  java
  • 421. Maximum XOR of Two Numbers in an Array 数组中两个数的最大异或

    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)





  • 相关阅读:
    xutils 上传文件 ,暂时
    UIView.FRAMEWORK
    2016.11.7
    2016.11.6新阶段开始
    远程推送
    xcode8 导入 dylib
    bugly使用
    anelife
    心阶段
    新阶段
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8331683.html
Copyright © 2011-2022 走看看