您的位置:首页 > 理论基础 > 数据结构算法

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

2016-12-25 23:18 525 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: