0
点赞
收藏
分享

微信扫一扫

421. Maximum XOR of Two Numbers in an Array

Silence潇湘夜雨 2022-08-03 阅读 23


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.

思路:
利用了异或的”自反性“: a ^ b = c,而a ^ b ^ b = a, 则 c ^ b = a
其他运算定律有:交换律、结合律、分配律。

class Solution {
public int findMaximumXOR(int[] nums) {
int max = 0;
int flag = 0;

// from left to right
for (int i = 31; i >= 0; i--) {
Set<Integer> prefixSet = new HashSet();
// flag : 11110000
flag = flag | (1 << i);
for (int num : nums) {
prefixSet.add(num & flag);
}

// tmp, max: 10101000000, add more 1
int tmp = max | (1 << i);
for (int prefix : prefixSet) {
// 利用了 ^ 的 a ^ b = c,则 b ^ c = a
if (prefixSet.contains(tmp ^ prefix)) {
max = tmp;
break;
}
}
}
return


举报

相关推荐

0 条评论