leetcode 421. Maximum XOR of Two Numbers in an Array

421. 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.


只能想出一个暴力解法。

class Solution {
public:
    int findMaximumXOR(vector<int>& nums) 
    {
        int ret = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i + 1; j < nums.size(); j++)
            {
                ret = max(ret, nums[j] ^ nums[i]);   
            }
        }
        return ret;
    }
};

网上找了个bit的解法。

按位遍历,题目中给定了数字的返回不会超过2^31,那么最多只能有32位,
我们用一个从左往右的mask,用来提取数字的前缀,然后将其都存入set中,
我们用一个变量t,用来验证当前位为1再或上之前结果res,看结果和set中的前缀异或之后在不在set中,这里用到了一个性质,若a^b=c,那么a=b^c,因为t是我们要验证的当前最大值,所以我们遍历set中的数时,和t异或后的结果仍在set中,说明两个前缀可以异或出t的值,所以我们更新res为t,继续遍历,如果上述讲解不容易理解,那么建议自己带个例子一步一步试试,并把每次循环中set中所有的数字都打印出来,基本应该就能理解了


class Solution {
public:
    int findMaximumXOR(vector<int>& nums) 
    {
        int res = 0, mask = 0;
        for (int i = 31; i >= 0; --i) 
        {
            mask |= (1 << i);
            set<int> s;
            for (int num : nums) 
            {
                s.insert(num & mask);
            }
            int t = res | (1 << i);
            for (int prefix : s) 
            {
                //证明set中存在一个数x使得 x ^ prefix = t 那t就是最新的最大的
                if (s.count(t ^ prefix)) 
                {
                    res = t;
                    break;
                }
            }
        }
        return res;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值