Maximum XOR of Two Numbers in an Array

130 阅读1分钟

位运算Trie

题目

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

Example 1:

Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.

Example 2:

Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127

Constraints:

  • 1 <= nums.length <= 2 * 105
  • 0 <= nums[i] <= 231 - 1

解答

  1. Brute Force就是两层循环,每两个数字都做一个XOR保留最大的值 O(N2)
  2. 讨论一个子问题:给定一个数字x,找x和数组nums[]中的XOR的最大值。XOR要最大,即希望最高位的bit是不相同的,次高位的bit不相同....根据这个建立一个Trie树
class Solution {
    class Node {
        Map<Integer, Node> children;
        public Node(){
            this.children = new HashMap<>();
        }
    }
    
    class ITrie {
        Node root;
        public ITrie() {
            this.root = new Node();
        }
        
        public void insert(int[] nums) {
            for (int num : nums) {
                Node cur = this.root;
                for (int i = 31; i >= 0; i-- ) {
                    int thisBit = (num >> i) & 1;
                    if (!cur.children.containsKey(thisBit)) {
                        cur.children.put(thisBit, new Node());
                    }
                    cur = cur.children.get(thisBit);
                }
            }
        }
    }
    
    public int findMaximumXOR(int[] nums) {
        ITrie trie = new ITrie();
        trie.insert(nums);
        int max = 0;
        
        for (int num : nums) {
            Node node = trie.root;
            int curSum = 0;
            for (int i = 31; i >= 0 ; i--) {
                int requiredBit = 1-((num >> i) & 1);
                if (node.children.containsKey(requiredBit)) {
                    curSum += (1 << i);
                    node = node.children.get(requiredBit);
                } else {
                    node = node.children.get(1-requiredBit);
                }
            }
            max = Math.max(max, curSum);
        }
        return max;
    }
}