421. Maximum XOR of Two Numbers in an Array

本文介绍了一种利用前缀树解决寻找数组中两个数最大异或值的方法。通过构建前缀树来存储数组中的每个元素,并通过比较每个元素与树中其他元素找到最大的异或结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

421. Maximum XOR of Two Numbers in an Array

description

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.

Use prextree to finish this task.

1 build prefix-tree which contain every element in vector from significant bit to least bit which is binary tree.

2 compare every element in vector to binary tree to find the largest element. Here is trick is that the maximum is with significant different number.

3 go throught the whole vector to get the maximum result.

implementation

class TrieNode {
public:
    TrieNode* next[2];
    TrieNode() {
        this->next[0] = NULL, this->next[1] = NULL;
    }
};

class Solution {
public:
    TrieNode* root = NULL;

    void buildTrieTree(vector<int>& nums) {
        int len = nums.size();
        if(!len) return;
        this->root = new TrieNode();
        TrieNode* cur = this->root;
        for(int ind = 0; ind < len; ind++) {
            int tmp = nums[ind];
            cur = this->root;
            for(int k = 31; k >= 0; k--) {
                int tree_node = (tmp >> k) & 1;
                if(!cur->next[tree_node]) 
                    cur->next[tree_node] = new TrieNode();
                cur = cur->next[tree_node];    
            }
        }
    }

    int calculateMax(int element) {
        int res = 0;
        TrieNode* cur = this->root;
        for(int i = 31; i >= 0; i--) {
            int dir = 1 - (element >> i) & 1; 
            if(cur->next[dir]) {
                res <<= 1;
                res |= 1;
            }   
            else {
                res <<= 1;
                dir = 1 - dir;
            }
            cur = cur->next[dir];
        }
        return res;
    }

    int findMaximumXOR(vector<int>& nums) {
        buildTrieTree(nums);
        int res = 0;
        for(auto ele:nums)
            res = max(calculateMax(ele), res);
        return res;    
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值