您的位置:首页 > 其它

[LeetCode]421. Maximum XOR of Two Numbers in an Array

2017-02-28 09:53 471 查看
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/?tab=Description

找出数组中两个数异或的最大值

解法一:

Trie树

字典树两个函数:1、search;2、insert

注意记录isNum的地方要用“或”,避免覆盖

public class Solution {
public int findMaximumXOR(int[] nums) {
TreeNode root = new TreeNode();
int res = Integer.MIN_VALUE;
for (int num : nums) {
res = Math.max(res, search(root, num, 31));
insert(root, num, 31);
}
return res;
}
private int search(TreeNode root, int num, int index) {
if (index < 0 || root == null) {
return 0;
}
boolean zero = (num & (1 << index)) == 0;
if (zero && root.one != null) {
return (1 << index) + search(root.one, num, index - 1);
} else if (!zero && root.zero != null) {
return (1 << index) + search(root.zero, num, index - 1);
} else {
return Math.max(search(root.one, num, index - 1), search(root.zero, num, index - 1));
}
}
private void insert(TreeNode root, int num, int index) {
if (index < 0) {
return;
}
boolean zero = (num & (1 << index)) == 0;
if (zero && root.zero == null) {
root.zero = new TreeNode();
root.zero.isNum |= (index == 0);
} else if (!zero && root.one == null) {
root.one = new TreeNode();
root.one.isNum |= (index == 0);
}
insert(zero ? root.zero : root.one, num, index - 1);
}
}
class TreeNode {
boolean isNum;
TreeNode zero;
TreeNode one;
}

解法二:

位运算

外层遍历找到最高位到第i位异或的最大值,greedyTry是用来假设当前位异或之后可以取一,如果确实当前位异或之后取一的话,那么set中两个数异或值为greedyTry,借助注释性质可得解

public class Solution {
public int findMaximumXOR(int[] nums) {
int res = 0;
int mask = 0;
for (int i = 31; i >= 0; i--) {
HashSet<Integer> set = new HashSet();
mask |= (1 << i);
for (int num : nums) {
set.add((num & mask));
}
int greedyTry = (res | (1 << i));
for (int leftNum : set) {
// a ^ b = c ==>> a ^ c = b
if (set.contains((leftNum ^ greedyTry))) {
res = greedyTry;
break;
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: