1. Question
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai< 231.
Find the maximum result of aiXOR 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.
2. Implementation
(1) Brute Force
class Solution {
public int findMaximumXOR(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
max = Math.max(max, nums[i] ^ nums[j]);
}
}
return max;
}
}
(2) Bit Manipulation + Trie
class Solution {
class TrieNode {
TrieNode[] childNode;
public TrieNode() {
childNode = new TrieNode[2];
}
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(int num) {
TrieNode curNode = root;
for (int i = 31; i >= 0; i--) {
int bit = (num >>> i) & 1;
if (curNode.childNode[bit] == null) {
curNode.childNode[bit] = new TrieNode();
}
curNode = curNode.childNode[bit];
}
}
}
public int findMaximumXOR(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
Trie trie = new Trie();
for (int num : nums) {
trie.insert(num);
}
int max = 0;
for (int num : nums) {
int curSum = 0;
TrieNode curNode = trie.root;
for (int i = 31; i >= 0; i--) {
int bit = (num >>> i) & 1;
if (curNode.childNode[bit ^ 1] != null) {
curSum |= (1 << i);
curNode = curNode.childNode[bit ^ 1];
}
else {
curNode = curNode.childNode[bit];
}
}
max = Math.max(max, curSum);
}
return max;
}
}
3. Time & Space Complexity
Brute Force: 时间复杂度O(n^2), 空间复杂度O(1)
Bit Manipulation + Trie: 时间复杂度O(n), 空间复杂度O(n)