Leetcode 421. Maximum XOR of Two Numbers in an Array 最大Xor和 解题报告【待理解】

1 解题思想

老实说,这道题我不太会做。。我是看了Discuss的,贴了个优秀解

我自己的那个是略显暴力的,但依然是O(N),只是依然TLE

不过两个解法的核心都是:
a^b = c ->a^c=b,b^c=a
当然你也可以用其他方法计算,只是运用位运算这种我不太熟悉,其他方法我也不想去写。。所以就先这样吧,等待更新ing

2 原题

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?
Example: 
Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.


Subscribe to see which companies asked this question

3 AC解

//来自Dicuss
public class Solution {

    // a^b = c ->a^c=b,b^c=a
    public int findMaximumXOR(int[] nums) {
        int max = 0, mask = 0;
        for(int i = 31; i >= 0; i--){
            //mask从0x01 ->0x03等一直变化,取后i位
            mask = mask | (1 << i);
            Set<Integer> set = new HashSet<>();
            for(int num : nums){
                set.add(num & mask);
            }
            //tmp表示当前的最大
            int tmp = max | (1 << i);
            System.out.println(mask+"  "+tmp+"  "+max);
            for(int prefix : set){
                //证明存在一个数使得tmp^x = prefix
                if(set.contains(tmp ^ prefix)) {
                    max = tmp;
                    break;
                }
            }
        }
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值