421. Maximum XOR of Two Numbers in an Array
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.
Approach
- 题目大意就是找到任意两个数异或之后的最大值。题目要求是要用线性的时间,一开始自己还是想不出什么办法,只能先暴力求解,发现超时,数据量上万左右,然后看到讨论区有比较易懂不复杂的解决办法,就是构建只有两位的字典树或者二叉树,然后查找数组中的每个数与它异或之后可能的最大值。
Code
struct BinaryTrie
{
BinaryTrie *next[2];
BinaryTrie() {
next[0] = nullptr;
next[1] = nullptr;
}
};
class Solution {
public:
void Insert_num(BinaryTrie* &root, int num) {
BinaryTrie*cur = root;
for (int i = 31; i >= 0; --i) {
int c = ((num >> i) & 1);
if (!cur->next[c]) {
cur->next[c] = new BinaryTrie();
}
cur = cur->next[c];
}
}
BinaryTrie* BuildBinaryTrie(vector<int>&nums) {
BinaryTrie* root = new BinaryTrie();
for (const int& num : nums) {
Insert_num(root, num);
}
return root;
}
int helper(BinaryTrie* &root, int num) {
int res = 0;
BinaryTrie *cur = root;
for (int i = 31; i >= 0; --i) {
int c = ((num >> i) & 1) ? 0 : 1;
if (cur->next[c]) {
res |= (1 << i);
cur = cur->next[c];
}
else {
cur = cur->next[c ? 0 : 1];
}
}
return res;
}
int findMaximumXOR(vector<int>& nums) {
BinaryTrie *root = BuildBinaryTrie(nums);
int maxn = 0;
for (const int&n : nums) {
maxn = max(maxn, helper(root, n));
}
return maxn;
}
};