【leetcode】421. Maximum XOR of Two Numbers in an Array

时间:2023-03-08 18:05:12

题目如下:

【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 = ''*(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 = '' * (MAX_LEN - len(bin(i)[2:])) + bin(i)[2:]
node = root
for b in i:
if len(node) == 0:
break
ib = '' if b == '' else ''
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