首页 > 代码库 > LeetCode Maximum XOR of Two Numbers in an Array

LeetCode Maximum XOR of Two Numbers in an Array

原题链接在这里:https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/

题目:

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 ≤ ij < 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.

题解:

利用Trie. 每个TrieNode.nexts array有两个分支,一个0, 一个1.

把nums中每一个num插入Trie中.

然后,对于一个num, 从首位bit开始,若是该bit^1对应的TrieNode存在,就说明nums中有该bit位和num是相反的数存在. 就沿着bit^1的分支走下去. 同时更新这个bit到这个num的sum中.

若bit^1对应的TrieNode 是null, 说明nums中没有该bit位和num相反的数存在,沿着该bit的分支走下去。

最后返回所有数中最大的res.

Time Complexity: O(n). n = nums.length. insert 用了O(n). 求res也用了O(n).

Space: O(1). Trie最大2^32-1.

AC Java:

 1 public class Solution {
 2     public int findMaximumXOR(int[] nums) {
 3         TrieNode root = new TrieNode();
 4         
 5         //insert each num into trie
 6         for(int num : nums){
 7             TrieNode p = root;
 8             for(int i = 31; i>=0; i--){
 9                 int curBit = (num>>>i)&1;
10                 if(p.nexts[curBit] == null){
11                     p.nexts[curBit] = new TrieNode();
12                 }
13                 p = p.nexts[curBit];
14             }
15         }
16         
17         int res = Integer.MIN_VALUE;
18         for(int num : nums){
19             TrieNode p = root;
20             int sum = 0;
21             for(int i = 31; i>=0; i--){
22                 int curBit = (num>>>i)&1;
23                 if(p.nexts[curBit^1] != null){
24                     sum += (1<<i);
25                     p = p.nexts[curBit^1];
26                 }else{
27                     p = p.nexts[curBit];
28                 }
29             }
30             res = Math.max(res, sum);
31         }
32         return res;
33     }
34 }
35 
36 class TrieNode{
37     TrieNode [] nexts;
38     public TrieNode(){
39         nexts = new TrieNode[2];
40     }
41 }

 

LeetCode Maximum XOR of Two Numbers in an Array