Leetcode Maximum XOR of Two Numbers in an Array

本文介绍了一种求解数组中两数异或最大值的高效算法。通过枚举每位上的数字并利用异或特性,结合字典树优化查询过程。提供两种实现方案:一种使用C++标准库中的map进行前缀匹配;另一种采用自定义字典树结构提高查找效率。

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

题意:给出一列数组,求出其中两个数字异或的最大值。
思路:这题的思路很巧妙,枚举了每个位上的数字。又利用的异或的性质。
class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        int mask = 0;
        int re = 0;
        for(int i = 31; i >=0; -- i) {
            mask |= (1 << i);
            map<int, bool> prefix;
            for(int j = 0; j < nums.size(); ++ j) {
                prefix[mask & nums[j]] = true;
            }
            
            int temp = re;
            temp |= (1 << i);
            for(int j = 0; j < nums.size(); ++ j) {
                if(prefix[temp ^ (nums[j] & mask)]) re = temp;
            }
        }
        
        return re;
    }
};

当查询某个数是否存在时,可以用字典树,而不是用map。

class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        TrieTree* root = buildTrieTree(nums);
        //root = root->buildTrieTree(nums);
        int re = 0;
        for(int i = 0; i < nums.size(); ++ i) {
            re = max(re, findIt(root, nums[i]));
        }
        
        return re;
    }
    
private:
    class TrieTree {
    public:
        TrieTree* c[2];
        TrieTree() {
            c[0] = NULL, c[1] = NULL;
        };
    };
        TrieTree* buildTrieTree(vector<int> nums) {
            TrieTree* root = new TrieTree(), *next = NULL;
            for(int i = 0; i < nums.size(); ++ i) {
                int num = nums[i]; //cout << num << endl;
                next = root;
                
                for(int j = 31; j >=0; --j) {
                    bool bit = (num >> j) & 1; //cout <<num << ((num >>= j) & 1) << endl;
                    if(next->c[bit]) {
                        next = next->c[bit];
                    }
                    else {
                        TrieTree* child = new TrieTree();
                        next->c[bit] = child;
                        next = child;
                    }
                }
            }
            
            return root;
        }

    
    int findIt(TrieTree* root, int num) {
        int re = 0;
        int rnum = ~num;
        
        for(int i = 31; i >=0; -- i) {
            bool bit =(rnum >> i) & 1;
            if(root->c[bit]) {
                re |= (1 << i);
                root = root->c[bit];
            }
            else {
                root = root->c[!bit];
            }
        }
        
        return re;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值