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 @   bonelee  阅读(379)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示