Leetcode 421

5 篇文章 0 订阅

给定一个数组,求两个数异或后的值最大是多少

 

 

sol: 注意到异或一个性质, 如果a^b=c那么 b^c=a

 

详细的题解看这里, https://kingsfish.github.io/2017/12/15/Leetcode-421-Maximum-XOR-of-Two-Numbers-in-an-Array/

写的非常好

 

 

    public int findMaximumXOR(int[] nums) {
        int res = 0;
        for (int i = 30; i >= 0; i--) {
            int mask = 1 << i;
            res |= mask;
            Set<Integer> set = new HashSet<>();
            for (int x : nums) set.add(x & res);
            boolean f = false;
            for (int x : set) {
               
                if (set.contains(x ^ res)) {
                    //该位能取到1
                    f = true;
                    break;
                }
            }
            //该位取不到1,置为0
            if (!f) res ^= mask;
        }
        return res;
    }

 

 

这题还有一种做法,是构建一颗数,然后每个数都沿着和当前位相反的方向走(异或才会大),取最大值.

https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/91059/java-on-solution-using-trie

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值