Leetcode Maximum XOR of Two Numbers in an Array

题意:给出一列数组,求出其中两个数字异或的最大值。
思路:这题的思路很巧妙,枚举了每个位上的数字。又利用的异或的性质。
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;
    }
};


猜你喜欢

转载自blog.csdn.net/markpen/article/details/67162818