zoukankan      html  css  js  c++  java
  • 【leetcode】421. Maximum XOR of Two Numbers in an Array

    题目如下:

    解题思路:本题的难点在于O(n)的复杂度。为了减少比较的次数,我们可以采用字典树保存输入数组中所有元素的二进制的字符串。接下来就是找出每个元素的异或的最大值,把需要找最大值的元素转成二进制表达后逐位在字典树中查找,查找的时候优先匹配反码,反码不存在则用原码。

    代码如下:

    class Solution(object):
        def findMaximumXOR(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            MAX_LEN = 31
            root = {}
            for i in nums:
                node = root
                i = '0'*(MAX_LEN-len(bin(i)[2:])) + bin(i)[2:]
                for b in i:
                    if b not in node:
                        node[b] = {}
                    node = node[b]
            #print root['0']['0']['0']['1']['1']
            res = 0
            for i in nums:
                path = ''
                i = '0' * (MAX_LEN - len(bin(i)[2:])) + bin(i)[2:]
                node = root
                for b in i:
                    if len(node) == 0:
                        break
                    ib = '1' if b == '0' else '0'
                    if ib in node:
                        node = node[ib]
                        path += ib
                    else:
                        node = node[b]
                        path += b
                #print i,path,int(i,2),int(path,2)
                res = max(res,int(i,2)^int(path,2))
            return res
  • 相关阅读:
    读取csv文件时编码错误
    ubuntu keras
    ubuntu19.1 tensorflow
    随机数random
    获取文件夹下所有文件名
    np.random.send()
    tensorflow---识别图像特征(吴恩达课程)
    Springboot项目热部署-Devtools
    Hadoop综合大作业
    分布式文件系统HDFS 练习
  • 原文地址:https://www.cnblogs.com/seyjs/p/9713475.html
Copyright © 2011-2022 走看看