题目:
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.
对应链接为:https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/#/description
解题思路:
1.由于是异或的最大值,必然需要从高位开始寻找,也就是说所有数据里面的最高位是否是最终结果。
2.这道题采用位运算里面的尝试判断,其实就是遍历所有情况,从当前数据的最高位开始,每一次都需要判断当前值是否可以有当前所有值的异或计算得出。由于在查找过程中,直接使用set,所以时间复杂度符合题目要求。
具体代码如下:
public class Solution {
public int findMaximumXOR(int[] nums) {
int max = 0;
int mask = 0;
for(int i=31;i>=0;i--){
mask = mask | (1<<i); //主要作用是用来选取所有数的最高位
Set<Integer> set = new HashSet<>();
for(int num : nums){
set.add(num & mask); //与操作选取最高位
}
int temp = max | (1<<i); //假设当前最高位的值是可以异或计算得到的结果。然后从高位开始试,一个一个尝试是不是可以由两个数值异或得到
for(int num : set){
if(set.contains(temp ^ num)){//如果存在两个数异或得到该值,则保留该位为1,结束。否则该位为0.
max = temp;
break;
}
}
}
return max;
}
}