sweet1cris

Untitled

Dec 26th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. class Solution {
  2.     public int findMaximumXOR(int[] nums) {
  3.         Trie trie = new Trie();
  4.         for (int num : nums) {
  5.             trie.insert(num);
  6.         }
  7.         int max = Integer.MIN_VALUE;
  8.        
  9.         for (int num : nums) {
  10.             TrieNode cur = trie.root;
  11.             int curSum = 0;
  12.             for (int i = 31; i >= 0; i--) {
  13.                 int curBit = (num >>>i) & 1;
  14.                 TrieNode next = cur.children[curBit ^ 1];
  15.                 if (next == null) {
  16.                     cur = cur.children[curBit];
  17.                 } else {
  18.                     curSum += (1 << i);
  19.                     cur = next;
  20.                 }
  21.             }
  22.             max = Math.max(max, curSum);
  23.         }
  24.         return max;
  25.     }
  26. }
  27. class TrieNode {
  28.     TrieNode[] children = new TrieNode[2];
  29. }
  30. class Trie {
  31.     TrieNode root = new TrieNode();
  32.     public Trie() {}
  33.     public void insert(int num) {
  34.         TrieNode cur = root;
  35.         for (int i = 31; i >= 0; i--) {
  36.             int curBit = (num >>> i) & 1;
  37.             TrieNode next = cur.children[curBit];
  38.             if (next == null) {
  39.                 next = new TrieNode();
  40.                 cur.children[curBit] = next;
  41.             }
  42.             cur = next;
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment