421. Maximum XOR of Two Numbers in an Array——本质:利用trie数据结构查找

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(object):
    def findMaximumXOR(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        [3,10,5]
        0x11, 
      0x1010, 
       0x101, 
     0x11001, 
        0x10, 
       0x100
-------------

        """
        root = [None]*2
        for num in nums:
            self.build_trie(root, num)
        ans = 0
        for num in nums:
            ans = max(ans, self.max_xor_of(root, num))
        return ans
        
    def build_trie(self, root, num):
        for i in range(30, -1, -1):
            flag = 1 if (num & (1<<i)) else 0
            if root[flag] is None:
                root[flag] = [None]*2
            root = root[flag]
    
    def max_xor_of(self, root, num):
        ans = 0
        for i in range(30, -1, -1):
            flag = 0 if (num & (1<<i)) else 1
            if root is None:
                break
            if root[flag] is not None:
                ans |= (1<<i)
                root = root[flag]
            else:
                root = root[1-flag]
        return ans                    

 

posted @ 2016-12-25 23:18  bonelee  阅读(377)  评论(0编辑  收藏  举报