LeetCode 421. 数组中两个数的最大异或值 Java 前缀树
作者:互联网
Java 前缀树
链接:https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/solution/java-qian-zhui-shu-by-oyzg-ualc/
这里我只画了5和25了
代码:
class Solution {
class Node {
//只有0和1两种可能
Node[] children = new Node[2];
}
static final int MAX_BIT = 31;
static final int MIN_BIT = 0;
Node root = new Node();
//获得n的i比特位
public int getBit(int n, int i) {
return (n>>>i)&1;
}
//初始化前缀树
public void init_trie(int[] nums) {
for(int num : nums) {
Node cur = root;
for(int i = MAX_BIT; i >= MIN_BIT; i--) {
int bit = getBit(num, i);
Node node = cur.children[bit];
if(node == null) {
node = new Node();
cur.children[bit] = node;
}
cur = node;
}
}
}
//求最大异或值
public int helper(int[] nums) {
int ans = Integer.MIN_VALUE;
for(int num : nums) {
Node cur = root;
int sum = 0;
for(int i = MAX_BIT; i >= MIN_BIT; i--) {
int bit = getBit(num, i);
int xorBit = bit^1;
//如果有和num的第i位相反的,就往反的这边走
Node node = cur.children[xorBit];
if(node == null) {
node = cur.children[bit];
} else {
sum += (1<<i);
}
cur = node;
}
ans = Math.max(ans, sum);
}
return ans;
}
public int findMaximumXOR(int[] nums) {
init_trie(nums);
return helper(nums);
}
}
标签:node,Node,Java,cur,nums,int,异或,421,BIT 来源: https://blog.csdn.net/weixin_46100881/article/details/116883796