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:
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
head = self.buildTrie(nums)
maxXor = 0
for num in nums:
node = head
curXor = 0
for bit in range(31, -1, -1):
chd = int(bool(num & (1 << bit)))
if node[1 ^ chd]:
curXor |= 1 << bit
node = node[1 ^ chd]
else:
node = node[chd]
maxXor = max(maxXor, curXor)
return maxXor
def buildTrie(self, nums):
root = [None, None]
for num in nums:
cur = ‘{0:b}‘.format(num).zfill(32)
node = root
for i in cur:
bit = int(i)
if not node[bit]:
node[bit] = [None, None]
node = node[bit]
return root
nums = [3, 10, 5, 25, 2, 8]
s = Solution()
res = s.findMaximumXOR(nums)
print(res)
原文地址:https://www.cnblogs.com/xiejunzhao/p/8331683.html
时间: 2024-10-30 02:04:23