lifeiteng

421. Maximum XOR of Two Numbers in an Array

Sep 24th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. class Solution {
  2.     public int findMaximumXOR(int[] nums) {
  3.         if(nums == null || nums.length < 2) return 0;
  4.         Node r = new Node();
  5.         int max = nums[0];
  6.         for(int k : nums)
  7.         {
  8.             Node root = r;
  9.             max = Math.max(max, k);
  10.             for(int i = 31; i >= 0; i--)
  11.             {
  12.                 if((k & (1 << i)) != 0)
  13.                 {
  14.                     if(root.left == null) root.left = new Node();
  15.                     root = root.left;
  16.                 }
  17.                 else
  18.                 {
  19.                     if(root.right == null) root.right = new Node();
  20.                     root = root.right;
  21.                 }
  22.             }
  23.         }
  24.         int xor = 0;
  25.         for(int k : nums)
  26.         {
  27.             Node root = r;
  28.             int curxor = 0;
  29.             for(int i = 31; i >= 0; i--)
  30.             {
  31.                 curxor <<= 1;
  32.                 if((k & (1 << i)) != 0)
  33.                 {
  34.                     if(root.right != null) root = root.right;
  35.                     else
  36.                     {
  37.                         root = root.left;
  38.                         curxor |= 1;
  39.                     }
  40.                 }
  41.                 else
  42.                 {
  43.                     if(root.left != null)
  44.                     {
  45.                         root = root.left;
  46.                         curxor |= 1;
  47.                     }
  48.                     else root = root.right;
  49.                 }
  50.             }
  51.             xor = Math.max(xor, k ^ curxor);
  52.         }
  53.         return xor;
  54.     }
  55. }
  56.  
  57. class Node
  58. {
  59.     Node left, right;
  60. }
Add Comment
Please, Sign In to add comment