1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| class Solution { struct TrieNode { TrieNode* zero = nullptr; TrieNode* one = nullptr; int count = 0; int minValue = numeric_limits<int>::max(); }; void insert(TrieNode* root, const int i, const int num) { ++root->count; root->minValue = min(root->minValue, num); if (i >= 0) { if (num & (1 << i)) { if (root->one == nullptr) root->one = new TrieNode(); insert(root->one, i - 1, num); } else { if (root->zero == nullptr) root->zero = new TrieNode(); insert(root->zero, i - 1, num); } } } int recurseQuery(TrieNode* root, const int x, const int limit, const int i, const int ans) { if (i < 0) return ans; if (x & (1 << i)) { if (root->zero && root->zero->count > 0) { return recurseQuery(root->zero, x, limit, i - 1, ans | (1 << i)); } else if (root->one && root->one->count > 0) { return recurseQuery(root->one, x, limit, i - 1, ans); } else { return -1; } } else { if (root->one && root->one->count > 0 && root->one->minValue <= limit) { return recurseQuery(root->one, x, limit, i - 1, ans | (1 << i)); } else if (root->zero && root->zero->count > 0) { return recurseQuery(root->zero, x, limit, i - 1, ans); } else { return -1; } } } public: vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) { const int maxDigit = 29; TrieNode* root = new TrieNode(); for (int i : nums) { insert(root, maxDigit, i); } const int q = queries.size(); vector<int> ans(q, -1); for (int i = 0; i < q; ++i) { const int x = queries[i][0]; const int m = queries[i][1]; if (root->minValue > m) { ans[i] = -1; } else { ans[i] = recurseQuery(root, x, m, maxDigit, 0); } } return ans; } };
|