Java implementation LeetCode 421 largest array of exclusive-OR value of two numbers

XOR array 421. The maximum value of the two numbers

Given a non-empty array, the array elements a0, a1, a2, ..., an-1, where 0 ≤ ai <231.

Finding the maximum exclusive OR (XOR) operation results ai and aj, where 0 ≤ i, j <n.

You can solve this problem in O (n) time?

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The biggest result is ^ 25 = 28. The 5
PS:
prefix tree

class Solution {
      
    class TrieNode {

        TrieNode zero;

        TrieNode one;

        int val;

        TrieNode() {

        }
    }

    class Trie {

        TrieNode root;

        Trie() {
            root = new TrieNode();
        }

        void insert(int num) {
            TrieNode node = root;
            for (int i = 31; i >= 0; i--) {
                int bit = num & (1 << i);
                if (bit == 0) {
                    if (node.zero == null) {
                        node.zero = new TrieNode();
                    }
                    node = node.zero;
                } else {
                    if (node.one == null) {
                        node.one = new TrieNode();
                    }
                    node = node.one;
                }
            }
            node.val = num;
        }

        int find(int num) {
            TrieNode node = root;
            for (int i = 31; i >= 0; i--) {
                int bit = num & (1 << i);
                if (bit == 0) {
                    node = node.one == null ? node.zero : node.one;
                } else {
                    node = node.zero == null ? node.one : node.zero;
                }
            }
            return node.val;
        }
    }

    // 数组中两个数的最大异或值
    public int findMaximumXOR(int[] nums) {
        Trie trie = new Trie();
        for (int num : nums) {
            trie.insert(num);
        }
        int res = 0;
        for (int num : nums) {
            int other = trie.find(num);
            res = Math.max(res, num ^ other);
        }
        return res;
    }
}
Released 1534 original articles · won praise 20000 + · views 2.09 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104879860
Recommended