421. Maximum XOR of Two Numbers in an Array

class Solution {
public:
    class TreeNode {
        public: //pay attention you need to make it public
            TreeNode *next[2];
            TreeNode() { next[0] = NULL; next[1] = NULL; };
    };

    void buildTrie(vector<int>& nums, TreeNode *root) {
        for (int i = 0; i < nums.size(); i++) {
            TreeNode *curr = root;
            for (int j = 30; j >= 0; j--) {
                int index = (nums[i] >> j) & 1;
                if (!curr->next[index])
                    curr->next[index] = new TreeNode;
                curr = curr->next[index];
            }
        }
        return;
    }

    int findMaximumXOR(vector<int>& nums) {
        TreeNode *root = new TreeNode();

        buildTrie(nums, root);

        int res = 0;
        for (int i = 0; i < nums.size(); i++) {
            int tmp = 0;
            TreeNode *curr = root;
            for (int j = 30; j >= 0; j--) {
                int index = 1 - ((nums[i] >> j) & 1);
                tmp = (tmp << 1) + 1;
                if (!curr->next[index]) {
                    index = 1 - index;
                    tmp--;
                }
                curr = curr->next[index];
            }
            res = max(res, tmp);
        }
        return res;
    }
};

results matching ""

    No results matching ""