给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 。
找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i, j < n 。
你能在O(n)的时间解决这个问题吗?
示例:
输入: [3, 10, 5, 25, 2, 8]
输出: 28
解释: 最大的结果是 5 ^ 25 = 28.
字典树 + 贪心:
1. 往字典树插入的时候,先插入高位,在插入低位
2. 字典树的数组大小开多少?题目给出的数据的个数 * 数据的位数,这里就是 N * 31 因为就算每个数插入字典树中都不会共用任何一个节点的话,每个数就需要31个节点,共N个数
3. 对于2^N大小的数来说的话,如果要取出每一位的话,需要右移的位数为 0 - (N - 1)
class Solution {
public:
int trie[31*100000][2],idx;
void insert(int num){
int p = 0;
for (int i = 30; i >= 0 ; --i){
int t = (num >> i) & 1;
if (trie[p][t] == 0) trie[p][t] = ++idx;
p = trie[p][t];
}
}
int query(int num){
int p = 0;
int ans = 0,level = 0;
for (int i = 30; i >= 0 ; --i){
int t = (num >> i) & 1;
if (trie[p][1-t]){
ans += (1 << i);
p = trie[p][1-t];
}else{
p = trie[p][t];
}
}
return ans;
}
int findMaximumXOR(vector<int>& nums) {
for (auto x:nums)
insert(x);
int max_num = 0;
for (auto x:nums)
max_num = max(max_num,query(x));
return max_num;
}
};