字典树、前缀树

421. 数组中两个数的最大异或值

给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 2^31 。

找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i,  j < n 。

你能在O(n)的时间解决这个问题吗?

class Solution {
public:
    int Max_xor=-1;
    string numToBinaryString(int n){
        string res="";
        for(int i=0;i<31;i++){
            if(( n & 1 )== 0)res="0"+res;
            else res="1"+res;
            n = n >> 1;
        }
        return res;
    }
    void MXOR(TreeNode* p, TreeNode* q,int k){
        if(p->val+q->val==1)k = k << 1 | 1;
        else k = k << 1;
        int c1=(p->left!=NULL)+(p->right!=NULL),c2=(q->left!=NULL)+(q->right!=NULL);
        if(c1==0&&c2==0){
            Max_xor=max(Max_xor,k);
            return;
        }
        if(c1==2&&c2==2){
            MXOR(p->left,q->right,k);
            MXOR(p->right,q->left,k);
        }
        else if(c1==2&&c2==1){
            if(q->left)
                MXOR(p->right,q->left,k);
            else
                MXOR(p->left,q->right,k);
        }
        else if(c1==1&&c2==2){
            if(p->left)
                MXOR(p->left,q->right,k);
            else
                MXOR(p->right,q->left,k);
        }
        else{
            TreeNode* a=p->left==NULL?p->right:p->left;
            TreeNode* b=q->left==NULL?q->right:q->left;
            MXOR(a,b,k);
        }
    }
    int findMaximumXOR(vector<int>& nums) {
        TreeNode* root=new TreeNode(0);
        TreeNode* p;
        
        for(int i=0;i<nums.size();i++){
            string res=numToBinaryString(nums[i]);
            p=root;
            int k=0;
            for(int j=0;j<res.length();j++){
                if(res[j]=='0'){
                    if(p->left==NULL){
                        TreeNode* tmp=new TreeNode(0);
                        p->left=tmp;
                    }
                    p=p->left;
                }
                else{
                    if(p->right==NULL){
                        TreeNode* tmp=new TreeNode(1);
                        p->right=tmp;
                    }
                    p=p->right;
                }
            }
        }
        int k=0;
        while((!root->left||!root->right)&&(root->left||root->right)){
            if(!root->left){
                root=root->right;
            }
            else{
                root=root->left;
            }
        }
        if(root->left==NULL&&root->right==NULL)return 0;
        MXOR(root->left, root->right,0);
        return Max_xor;
    }
};

 图片来源及官网题解:https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/solution/shu-zu-zhong-liang-ge-shu-de-zui-da-yi-huo-zhi-by-/

猜你喜欢

转载自www.cnblogs.com/Dancing-Fairy/p/12759077.html