421. Maximum XOR of Two Numbers in an Array
description
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: The maximum result is 5 ^ 25 = 28.
Use prextree to finish this task.
1 build prefix-tree which contain every element in vector from significant bit to least bit which is binary tree.
2 compare every element in vector to binary tree to find the largest element. Here is trick is that the maximum is with significant different number.
3 go throught the whole vector to get the maximum result.
implementation
class TrieNode {
public:
TrieNode* next[2];
TrieNode() {
this->next[0] = NULL, this->next[1] = NULL;
}
};
class Solution {
public:
TrieNode* root = NULL;
void buildTrieTree(vector<int>& nums) {
int len = nums.size();
if(!len) return;
this->root = new TrieNode();
TrieNode* cur = this->root;
for(int ind = 0; ind < len; ind++) {
int tmp = nums[ind];
cur = this->root;
for(int k = 31; k >= 0; k--) {
int tree_node = (tmp >> k) & 1;
if(!cur->next[tree_node])
cur->next[tree_node] = new TrieNode();
cur = cur->next[tree_node];
}
}
}
int calculateMax(int element) {
int res = 0;
TrieNode* cur = this->root;
for(int i = 31; i >= 0; i--) {
int dir = 1 - (element >> i) & 1;
if(cur->next[dir]) {
res <<= 1;
res |= 1;
}
else {
res <<= 1;
dir = 1 - dir;
}
cur = cur->next[dir];
}
return res;
}
int findMaximumXOR(vector<int>& nums) {
buildTrieTree(nums);
int res = 0;
for(auto ele:nums)
res = max(calculateMax(ele), res);
return res;
}
};