给定一个数组,求两个数异或后的值最大是多少
sol: 注意到异或一个性质, 如果a^b=c那么 b^c=a
详细的题解看这里, https://kingsfish.github.io/2017/12/15/Leetcode-421-Maximum-XOR-of-Two-Numbers-in-an-Array/
写的非常好
public int findMaximumXOR(int[] nums) {
int res = 0;
for (int i = 30; i >= 0; i--) {
int mask = 1 << i;
res |= mask;
Set<Integer> set = new HashSet<>();
for (int x : nums) set.add(x & res);
boolean f = false;
for (int x : set) {
if (set.contains(x ^ res)) {
//该位能取到1
f = true;
break;
}
}
//该位取不到1,置为0
if (!f) res ^= mask;
}
return res;
}
这题还有一种做法,是构建一颗数,然后每个数都沿着和当前位相反的方向走(异或才会大),取最大值.