LeetCode 421 Maximum XOR of Two Numbers in an Array (Python)

Posted by 小明MaxMing on September 16, 2020

题目

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?

解题思路

从最高位开始,先假设该位置可以为1,然后与每个数进行异或,查看结果是否也在输入的数中,如果不在,则该位为0

代码

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        res = 0
        for i in range(31, -1, -1):
            res <<= 1
            pre = {n >> i for n in nums}
            res += any(res ^ 1 ^ p in pre for p in pre)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅