421. Maximum XOR of Two Numbers in an Array

来源:互联网 发布:软件如何创建快捷方式 编辑:程序博客网 时间:2024/05/22 20:28

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: 28Explanation: The maximum result is 5 ^ 25 = 28.


对应不同的位数,从高位到低位。注意|、和<<的优先级。

public class Solution {    public int findMaximumXOR(int[] nums) {        int mask=0,max=0;         for(int i=31;i>=0;i--){                   //对于每次循环,计算是否能够在当前max的基础上+2^i。            mask=mask|(1<<i);        HashSet<Integer>  set=new HashSet<>();        for(int num:nums){        set.add(num&mask);        }        int temp=max|(1<<i);        for(int numi:set){                     //temp为当前max+2^i,如果能够找到两个数异或之后等于temp,则max的值加2^i        if(set.contains(temp^numi)){        max=temp;        break;        }        }        }        return max;    }}

使用trie.  一共32层。

public class Solution {class Trie{Trie[] children;public Trie(){children=new Trie[2];}}    public int findMaximumXOR(int[] nums) {    if(nums == null || nums.length == 0) {              return 0;        }        Trie root=new Trie();        int max=0;        for(int num:nums){        Trie findnode=root,setnode=root;        int temp=0;        for(int i=31;i>=0;i--){        int curbit=(num>>>i)&1;                if(setnode.children[curbit]==null){     //建立trie树        setnode.children[curbit]=new Trie();        }        setnode=setnode.children[curbit];                if(findnode.children[curbit^1]!=null){                  //查找对应的数temp=temp|(1<<i);findnode=findnode.children[curbit^1];}else{findnode=findnode.children[curbit];}        }        max=Math.max(max, temp);        }        return max;    }}








0 0
原创粉丝点击