Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int findMaximumXOR(int[] nums) {
- Trie trie = new Trie();
- for (int num : nums) {
- trie.insert(num);
- }
- int max = Integer.MIN_VALUE;
- for (int num : nums) {
- TrieNode cur = trie.root;
- int curSum = 0;
- for (int i = 31; i >= 0; i--) {
- int curBit = (num >>>i) & 1;
- TrieNode next = cur.children[curBit ^ 1];
- if (next == null) {
- cur = cur.children[curBit];
- } else {
- curSum += (1 << i);
- cur = next;
- }
- }
- max = Math.max(max, curSum);
- }
- return max;
- }
- }
- class TrieNode {
- TrieNode[] children = new TrieNode[2];
- }
- class Trie {
- TrieNode root = new TrieNode();
- public Trie() {}
- public void insert(int num) {
- TrieNode cur = root;
- for (int i = 31; i >= 0; i--) {
- int curBit = (num >>> i) & 1;
- TrieNode next = cur.children[curBit];
- if (next == null) {
- next = new TrieNode();
- cur.children[curBit] = next;
- }
- cur = next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment