题目链接: 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.
思路: 之前的一篇博客有写过这个, 移步那里吧!
代码如下:
class Solution {
public:
struct Trie{
vector<Trie*> child;
Trie():child(vector<Trie*>(2, NULL)){}
};
void add(int num){
Trie* tem = root;
for(int i = 31; i >=0; i--){
int val = (num>>i)&1;
if(!tem->child[val]) tem->child[val] = new Trie();
tem = tem->child[val];
}
}
int search(int num){
int ans = 0;
Trie* tem = root;
for(int i = 31; i >= 0; i--){
int val = (num>>i)&1;
ans = ans<<1;
if(tem->child[val]) ans++, tem = tem->child[val];
else tem = tem->child[!val];
}
return ans;
}
int findMaximumXOR(vector<int>& nums) {
root = new Trie();
for(auto val: nums) add(val);
int ans = INT_MIN;
for(auto val: nums) ans = max(ans, search(~val));
return ans;
}
private:
Trie *root;
};