421. Maximum XOR of Two Numbers in an Array

https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/solution/li-yong-yi-huo-yun-suan-de-xing-zhi-tan-xin-suan-f/

两个数相同位置上1、0不同的位数越多,且越靠近高位,最后的结果越大

 

1. 异或运算就是二进制下不应用进位的加法
2. 如果 a ^ b = c成立, 那么 a ^ c = b, b ^ c = a也成立

421. Maximum XOR of Two Numbers in an Array_第1张图片

 

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        res = 0
        mask = 0
        for i in range(31, -1, -1):
            mask |= (1 << i)
            s = set()
            for num in nums:
                s.add(num & mask)
            tmp = res | (1 << i)
            for num in s:
                if tmp ^ num in s:
                    res = tmp
                    break
        return res

|  :  按位

你可能感兴趣的:(i,don't,know,哦豁,what??)