leetcode421. 数组中两个数的最大异或值

从上到下根据数的二进制建立字典树。然后根据贪心的准则自上而下每次尽量选择与当前值不同的节点向下选择
注意一下根据二进制恢复原数字的计算

class TireNode(object):
    def __init__(self,val):
        self.val = val
        self.children = {}
class Solution(object):
    def findMaximumXOR(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(format(max(nums),"b")) - 1   #二进制串的最长长度-1
        root = TireNode(-1)
        for num in nums:
            node = root
            for i in range(l,-1,-1):
                tmp = (num >> i)&1
                if tmp not in node.children:
                    node.children[tmp] = TireNode(tmp)
                node = node.children[tmp]

        res = 0
        for num in nums:
            node = root
            total = 0
            for i in range(l,-1,-1):
                v = (num >> i)&1         #当前这个数的二进制的位
                if 1-v in node.children:
                    total = total*2 + 1
                    node = node.children[1-v]
                else:
                    total = total*2
                    node = node.children[v]
            res = max(res,total)
        return res

你可能感兴趣的:(字典树Trie,算法,c++,leetcode)