leetcode 421 数组中的两个数的最大异或值

给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 。

找到 ai 和aj 最大的异或 (XOR) 运算结果,其中0 ≤ i,  j < n 。

你能在O(n)的时间解决这个问题吗?

示例:

输入: [3, 10, 5, 25, 2, 8]

输出: 28

解释: 最大的结果是 5 ^ 25 = 28.

这题挺别开生面的,当时,只有暴力,后来参考了评论区的答案,构建一个Tire(前缀树)来解决。

class Solution {
    class Trie {
        Trie[] child;
        public Trie() {
            child = new Trie[2];
        }
    }

    
    public int findMaximumXOR(int[] nums) {
        if (nums == null || nums.length == 0)
        return 0;
        Trie root = new Trie();
        for (int i = 0;i < nums.length;i++) {
            Trie cur = root;
            int num = nums[i];
            for (int j = 31;j >= 0;j--) {
                int X = (num >>> j) & 1;
                if (cur.child[X] == null) {
                    cur.child[X] = new Trie();
                }
                cur = cur.child[X];
            }
        }

        int res = 0;
        for (int i = 0;i < nums.length;i++) {
            Trie cur = root;
            int num = nums[i];
            int sum = 0;
            for (int j = 31;j >= 0;j--) {
                int X = (num >>> j) & 1;
                if (cur.child[X ^ 1] != null) {
                    sum += (1 << j);
                    cur = cur.child[X ^ 1];
                } else {
                    cur = cur.child[X];
                }
            }
            res = Math.max(res,sum);
        }
        return res;
    }
}
发布了315 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_39137699/article/details/104081282
421