Leetcode Maximum XOR of Two Numbers in an Array

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 ≤ ij < 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.

----------------------------------------------------------------------------------------

Cycle bit by bit. For every bit, we could know the largest prefix expected. If the expected largest prefix could be xor by some two nums (implemented by hashSet), we could know the final answer. The complexity is O(n)

class Solution:
    def findMaximumXOR(self, nums):
        pre, mask = 0, 0
        for i in range(31, -1, -1):
            one = (1 << i)
            mask |= one
            exist = set()
            cur_largest = pre | one

            for num in nums:
                cur = num & mask
                if ((cur ^ cur_largest) in exist):
                    pre = cur_largest
                else:
                    exist.add(cur)
        return pre
s = Solution()
print(s.findMaximumXOR([3, 10, 5, 25, 2, 8]))

 

Leetcode Maximum XOR of Two Numbers in an ArrayLeetcode Maximum XOR of Two Numbers in an Array taoqick 发布了210 篇原创文章 · 获赞 101 · 访问量 47万+ 他的留言板 关注
上一篇:QPropertyAnimation 几行代码快速制作流畅的动画效果


下一篇:【Leetcode_easy】628. Maximum Product of Three Numbers