您的位置:首页 > 编程语言 > Java开发

421. Maximum XOR of Two Numbers in an Array

2017-07-22 21:45 260 查看
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?

题解

使用trie树记录所有数的01二进制表示

之后遍历每个数,找出尽可能多的不同位的另一个数,进行异或,记录最大值

空间复杂度O(n),时间复杂度O(n)

class Trie {
Trie[] children;
public Trie() {
children = new Trie[2];
}
}

public class Solution {

public int findMaximumXOR(int[] nums) {
if(nums.length <= 1) return 0;
//用trie存储所有数的二进制表达
Trie root = new Trie();
for(int num: nums) {
Trie curNode = root;
for(int i = 31; i >= 0; i --) {
int curBit = (num >>> i) & 1;
if(curNode.children[curBit] == null) {
curNode.children[curBit] = new Trie();
}
curNode = curNode.children[curBit];
}
}

int max = Integer.MIN_VALUE;
for(int num: nums) {
Trie curNode = root;
int curSum = 0;
for(int i = 31; i >= 0; i --) {
int curBit = (num >>> i) & 1;
//尽可能取对应位相反
if(curNode.children[curBit ^ 1] != null) {
curSum += (1 << i);
curNode = curNode.children[curBit ^ 1];
}else {
curNode = curNode.children[curBit];
}
}
max = Math.max(curSum, max);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java Leetcode 算法