[WXM] LeetCode 421. Maximum XOR of Two Numbers in an Array C++

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

Approach

  1. 题目大意就是找到任意两个数异或之后的最大值。题目要求是要用线性的时间,一开始自己还是想不出什么办法,只能先暴力求解,发现超时,数据量上万左右,然后看到讨论区有比较易懂不复杂的解决办法,就是构建只有两位的字典树或者二叉树,然后查找数组中的每个数与它异或之后可能的最大值。

Code

struct  BinaryTrie
{
    BinaryTrie *next[2];
    BinaryTrie() {
        next[0] = nullptr;
        next[1] = nullptr;
    }
};
class Solution {
public:
    void Insert_num(BinaryTrie* &root, int num) {
        BinaryTrie*cur = root;
        for (int i = 31; i >= 0; --i) {
            int c = ((num >> i) & 1);
            if (!cur->next[c]) {
                cur->next[c] = new BinaryTrie();
            }
            cur = cur->next[c];
        }
    }
    BinaryTrie* BuildBinaryTrie(vector<int>&nums) {
        BinaryTrie* root = new BinaryTrie();
        for (const int& num : nums) {
            Insert_num(root, num);
        }
        return root;
    }
    int helper(BinaryTrie* &root, int num) {
        int res = 0;
        BinaryTrie *cur = root;
        for (int i = 31; i >= 0; --i) {
            int c = ((num >> i) & 1) ? 0 : 1;
            if (cur->next[c]) {
                res |= (1 << i);
                cur = cur->next[c];
            }
            else {
                cur = cur->next[c ? 0 : 1];
            }
        }
        return res;
    }
    int findMaximumXOR(vector<int>& nums) {
        BinaryTrie *root = BuildBinaryTrie(nums);
        int maxn = 0;
        for (const int&n : nums) {
            maxn = max(maxn, helper(root, n));
        }
        return maxn;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值