LeetCode #421: Maximum XOR of Two Numbers in an Array

129 篇文章 0 订阅

Problem Statement

(Source) Given a non-empty array of numbers, a0 , a1 , a2 , … , an1 , 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.

Solution

Tags: Trie, Bit Manipulation.

Self-explained code is as follows. The time complexity is O(n) as expected.

class Solution(object):
    def findMaximumXOR(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        arr = map(lambda x: bin(x)[2:].rjust(32, '0'), nums)
        pt = {}  # prefix tree

        def add(pt, x):
            for i in xrange(len(x)):
                if x[i] not in pt:
                    pt[x[i]] = {}
                pt = pt[x[i]]

        def calculate(pt, x):           
            t = []
            for i in xrange(len(x)):
                keys = pt.keys()
                if len(keys) == 1:
                    if x[i] in keys:
                        t.append('0')
                    else:
                        t.append('1')
                    pt = pt[keys.pop()]
                else:
                    keys.remove(x[i])
                    t.append('1')
                    pt = pt[keys.pop()]
            return int(''.join(t), base=2)


        res = 0
        add(pt, arr[0])
        for i in xrange(1, len(arr)):
            res = max(res, calculate(pt, arr[i]))
            add(pt, arr[i])
        return res
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值