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

来源:互联网 发布:.club域名与.com 编辑:程序博客网 时间:2024/06/05 07:34

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: 28Explanation: 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
原创粉丝点击