LeetCode 421. 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 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 cur = (num>>i)&1;
10                 if(p.nexts[cur] == null){
11                     p.nexts[cur] = new TrieNode();
12                 }
13                 
14                 p = p.nexts[cur];
15             }
16         }
17         
18         int res = 0;
19         for(int num : nums){
20             TrieNode p = root;
21             int sum = 0;
22             for(int i = 31; i>=0; i--){
23                 int cur = (num>>i)&1;
24                 if(p.nexts[cur^1] != null){
25                     sum += (1<<i);
26                     p = p.nexts[cur^1];
27                 }else{
28                     p = p.nexts[cur];
29                 }
30             }
31             
32             res = Math.max(res, sum);
33         }
34         
35         return res;
36     }
37 }
38 
39 class TrieNode{
40     TrieNode [] nexts;
41     
42     public TrieNode(){
43         nexts = new TrieNode[2];
44     }
45 }

 

posted @ 2017-02-01 08:41  Dylan_Java_NYC  阅读(509)  评论(0编辑  收藏  举报