[leetCode]421. 数组中两个数的最大异或值

题目

https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/

[leetCode]421. 数组中两个数的最大异或值_第1张图片

哈希表

class Solution {
    public int findMaximumXOR(int[] nums) {
        int maxNum = Arrays.stream(nums).max().getAsInt();
        // 最大数字的位数
        int L = Integer.toBinaryString(maxNum).length();

        int maxXor = 0, curXor;
        Set<Integer> prefixes = new HashSet<>();
        for (int i = L - 1; i >= 0; i--) {
            maxXor <<= 1;// 
            curXor = maxXor | 1;
            prefixes.clear();
            for (Integer num : nums) {
                prefixes.add(num >> i);
            }
            for (Integer p : prefixes) {
                if (prefixes.contains(curXor ^ p)) {
                    maxXor = curXor;
                }
            }
        }
        return maxXor;
    }
}

前缀树

class Solution {
    public int findMaximumXOR(int[] nums) {
        // 1. 计算最大的位数
        int maxNum = Arrays.stream(nums).max().getAsInt();
        int L = Integer.toBinaryString(maxNum).length();
        // 2. 将原数字转化为2进制字符串,bitMask保证字符串有5位
        int n = nums.length , bitMask = 1 << L, idx = 0;
        String[] strNums = new String[n];
        for (Integer num : nums) {
            strNums[idx++] = Integer.toBinaryString(bitMask | num);
        }

        TrieNode root = new TrieNode();
        int maxXor = 0;
        for (String num : strNums) {
            TrieNode cur = root, xorCur = root;
            int curXor = 0;
            for (char bit : num.toCharArray()) {
                cur = cur.children.computeIfAbsent(bit, k -> new TrieNode());
                char toggleBit = bit == '1' ? '0' : '1';
                
                if (xorCur.children.containsKey(toggleBit)) {
                    curXor = (curXor << 1) | 1;
                    xorCur = xorCur.children.get(toggleBit);
                } else {
                    curXor = curXor << 1;    
                    xorCur = xorCur.children.get(bit);
                } 
            }
            maxXor = Math.max(maxXor, curXor);
        }
        return maxXor;
    }

    class TrieNode {
        Map<Character, TrieNode> children;
        TrieNode() {
            children = new HashMap<>();
        } 
    }
}

你可能感兴趣的:(#,字符串)