Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 421. Maximum XOR of Two Numbers in an Array #299

Open
Woodyiiiiiii opened this issue Nov 4, 2023 · 0 comments
Open

Leetcode 421. Maximum XOR of Two Numbers in an Array #299

Woodyiiiiiii opened this issue Nov 4, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

421. Maximum XOR of Two Numbers in an Array

421. Maximum XOR of Two Numbers in an Array

这道题我没想到解法。用贪心的话不行,遍历数组的话只能两次遍历。

那么,这时候就要观察题目特性了,我们其实只需要关注数的二进制情况,而且数值之间有共用特性。

这就是字典树Trie数据结构。我们也不用标志位,直接用this和判空来验证数是否存在。

class Solution {
    public int findMaximumXOR(int[] nums) {
        int ans = 0;
        Trie trie = new Trie();
        for (int num : nums) {
            trie.insert(num);
        }
        for (int num : nums) {
            ans = Math.max(ans, trie.check(num));
        }
        return ans;
    }

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

        public void insert(int num) {
            Trie cur = this;
            for (int i = 31; i >= 0; i--) {
                int bit = (num >> i) & 1;
                if (cur.next[bit] == null) {
                    cur.next[bit] = new Trie();
                }
                cur = cur.next[bit];
            }
        }

        public int check(int num) {
            int max = 0;
            Trie cur = this;
            for (int i = 31; i >= 0; i--) {
                int bit = (num >> i) & 1;
                if (cur.next[bit ^ 1] != null) {
                    cur = cur.next[bit ^ 1];
                    max |= (1 << i);
                } else {
                    cur = cur.next[bit];
                }
            }
            return max;
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant