题目链接
https://leetcode.com/problems/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.
思路:
trie树基本题。trie树入门见【蒟蒻字符串】Trie树(字典树)
时间复杂度
O
(
31
∗
n
)
O(31*n)
O(31∗n)
根据题目中的样例可以构成trie树:
这并不是完整的图…完整的图从上到下每层应该依次表示num的第31位,第30位,…,第1位,第0位。每次新加入的num先和前面的数字构成的trie树求异或,最后将num也加入到trie树中。
class Solution {
public:
static const int N=999999;
int ch[N][2];
int tot=0;
void add(int num){//插入
int u=0;
for(int i=31;i>=0;i--){
int c=(num>>i)&1;
if(!ch[u][c]) ch[u][c]=++tot;//记录每个字符的位置
u=ch[u][c];
}
}
int quiry(int num){//查询
int u=0;
int sum=0;
for(int i=31;i>=0;i--){
int c=(num>>i)&1;
if(ch[u][c^1]){//如果c=1,那么要想异或值最大,需要走trie树的ch[u][0]分支;c=0同理
sum+=(1<<i);
u=ch[u][c^1];
}
else
u=ch[u][c];
if(!u) break;
}
return sum;
}
int findMaximumXOR(vector<int>& nums) {
int mx=0;
for(int i=0;i<nums.size();i++){
int ans=quiry(nums[i]);
mx=max(mx,ans);
add(nums[i]);
}
return mx;
}
};