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?
题解
使用trie树记录所有数的01二进制表示
之后遍历每个数,找出尽可能多的不同位的另一个数,进行异或,记录最大值
空间复杂度O(n),时间复杂度O(n)
class Trie {
Trie[] children;
public Trie() {
children = new Trie[2];
}
}
public class Solution {
public int findMaximumXOR(int[] nums) {
if(nums.length <= 1) return 0;
//用trie存储所有数的二进制表达
Trie root = new Trie();
for(int num: nums) {
Trie curNode = root;
for(int i = 31; i >= 0; i --) {
int curBit = (num >>> i) & 1;
if(curNode.children[curBit] == null) {
curNode.children[curBit] = new Trie();
}
curNode = curNode.children[curBit];
}
}
int max = Integer.MIN_VALUE;
for(int num: nums) {
Trie curNode = root;
int curSum = 0;
for(int i = 31; i >= 0; i --) {
int curBit = (num >>> i) & 1;
//尽可能取对应位相反
if(curNode.children[curBit ^ 1] != null) {
curSum += (1 << i);
curNode = curNode.children[curBit ^ 1];
}else {
curNode = curNode.children[curBit];
}
}
max = Math.max(curSum, max);
}
return max;
}
}