|
| 1 | +// Runtime: 603 ms (Top 88.8%) | Memory: 180.29 MB (Top 72.2%) |
| 2 | + |
1 | 3 | class Solution {
|
2 | 4 | public:
|
3 |
| - int findMaximumXOR(vector<int>& nums) { |
4 |
| - int ans=0,mask=0; |
5 |
| - unordered_set<int>st; |
6 |
| - for(int i=31;i>=0;i--){ |
7 |
| - mask|=(1<<i); |
8 |
| - int temp=ans|(1<<i); |
9 |
| - for (int j = 0; j < nums.size(); j++) { |
10 |
| - int num = nums[j] & mask; |
11 |
| - if (st.find(temp ^ num)!=st.end()) { |
12 |
| - ans = temp; |
13 |
| - break; |
| 5 | + struct TrieNode { |
| 6 | + //trie with max 2 child, not taking any bool or 26 size value because no need |
| 7 | + TrieNode* one; |
| 8 | + TrieNode* zero; |
| 9 | + }; |
| 10 | + void insert(TrieNode* root, int n) { |
| 11 | + TrieNode* curr = root; |
| 12 | + for (int i = 31; i >= 0; i--) { |
| 13 | + int bit = (n >> i) & 1; //it will find 31st bit and check it is 1 or 0 |
| 14 | + if (bit == 0) { |
| 15 | + if (curr->zero == nullptr) { //if 0 then we will continue filling on zero side |
| 16 | + TrieNode* newNode = new TrieNode(); |
| 17 | + curr->zero = newNode; |
| 18 | + } |
| 19 | + curr = curr->zero; //increase cur to next zero position |
| 20 | + } |
| 21 | + else { |
| 22 | + //similarly if we get 1 |
| 23 | + if (curr->one == nullptr) { |
| 24 | + TrieNode* newNode = new TrieNode(); |
| 25 | + curr->one = newNode; |
| 26 | + } |
| 27 | + curr = curr->one; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + int findmax(TrieNode* root, int n) { |
| 32 | + TrieNode* curr = root; |
| 33 | + int ans = 0; |
| 34 | + for (int i = 31; i >= 0; i--) { |
| 35 | + int bit = (n >> i) & 1; |
| 36 | + if (bit == 1) { |
| 37 | + if (curr->zero != nullptr) { //finding complement , if find 1 then we will check on zero side |
| 38 | + ans += (1 << i); //push values in ans |
| 39 | + curr = curr->zero; |
| 40 | + } |
| 41 | + else { |
| 42 | + curr = curr->one; //if we don't get then go to one's side |
14 | 43 | }
|
15 |
| - st.insert(num); |
16 | 44 | }
|
17 |
| - st.clear(); |
| 45 | + else { |
| 46 | + //similarly on zero side if we get 0 then we will check on 1 s side |
| 47 | + if (curr->one != nullptr) { |
| 48 | + ans += (1 << i); |
| 49 | + curr = curr->one; |
| 50 | + } |
| 51 | + else { |
| 52 | + curr = curr->zero; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return ans; |
| 57 | + } |
| 58 | + |
| 59 | + int findMaximumXOR(vector<int>& nums) { |
| 60 | + int n = nums.size(); |
| 61 | + TrieNode* root = new TrieNode(); |
| 62 | + int ans = 0; |
| 63 | + for (int i = 0; i < n; i++) { |
| 64 | + insert(root, nums[i]); //it will make trie by inserting values |
| 65 | + } |
| 66 | + for (int i = 1; i < n; i++) { |
| 67 | + ans = max(ans, findmax(root, nums[i])); //find the necessary complementory values and maximum store |
18 | 68 | }
|
19 | 69 | return ans;
|
20 | 70 | }
|
|
0 commit comments