1 解题思想
老实说,这道题我不太会做。。我是看了Discuss的,贴了个优秀解
我自己的那个是略显暴力的,但依然是O(N),只是依然TLE
不过两个解法的核心都是:
a^b = c ->a^c=b,b^c=a
当然你也可以用其他方法计算,只是运用位运算这种我不太熟悉,其他方法我也不想去写。。所以就先这样吧,等待更新ing
2 原题
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.
Subscribe to see which companies asked this question
3 AC解
//来自Dicuss
public class Solution {
// a^b = c ->a^c=b,b^c=a
public int findMaximumXOR(int[] nums) {
int max = 0, mask = 0;
for(int i = 31; i >= 0; i--){
//mask从0x01 ->0x03等一直变化,取后i位
mask = mask | (1 << i);
Set<Integer> set = new HashSet<>();
for(int num : nums){
set.add(num & mask);
}
//tmp表示当前的最大
int tmp = max | (1 << i);
System.out.println(mask+" "+tmp+" "+max);
for(int prefix : set){
//证明存在一个数使得tmp^x = prefix
if(set.contains(tmp ^ prefix)) {
max = tmp;
break;
}
}
}
return max;
}
}