Advertisement
sweet1cris

Untitled

Jan 9th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. public class Solution {
  2.     /*
  3.      * @param : the array
  4.      * @return: the max xor sum of the subarray in a given array
  5.      */
  6.     class TrieNode{
  7.         public int label;
  8.         public TrieNode[] children;
  9.         TrieNode(int label){
  10.             this.label = label;
  11.             this.children = new TrieNode[2];
  12.         }
  13.     }
  14.     public int maxXorSubarray(int[] nums) {
  15.         if(nums == null || nums.length == 0) return 0;
  16.         int max = 0;
  17.         int pre_xor = 0;
  18.         TrieNode root = new TrieNode(0);
  19.         for(int i=0;i<nums.length;i++){
  20.             pre_xor ^= nums[i];
  21.             insert(root, pre_xor);
  22.             max = Math.max(max, searchAndFindMax(root, pre_xor));
  23.         }
  24.         return max;
  25.     }
  26.    
  27.     private void insert(TrieNode root, int num){
  28.         TrieNode cur = root;
  29.         for(int i=31;i>=0;i--){
  30.             int bit = num >> i & 1;
  31.             if(cur.children[bit] == null){
  32.                 cur.children[bit] = new TrieNode(bit);
  33.             }
  34.             cur = cur.children[bit];
  35.         }
  36.     }
  37.    
  38.     private int searchAndFindMax(TrieNode root, int num){
  39.         TrieNode cur = root;
  40.         int res = 0;
  41.         for(int i=31;i>=0;i--){
  42.             int bit = num >> i & 1;
  43.             if(cur.children[1-bit] != null){
  44.                 res |= 1 << i;
  45.                 cur = cur.children[1-bit];
  46.             }else{
  47.                 cur = cur.children[bit];
  48.             }
  49.         }
  50.         return res;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement