knakul853

Untitled

Jun 12th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Trie{
  5.     public:
  6.     Trie* bit[2];
  7.     bool leaf;
  8.    
  9.     Trie()
  10.     {
  11.         for(int i=0;i<2;i++)bit[i] = NULL;
  12.         leaf = false;
  13.     }
  14. };
  15.  
  16. class Solution {
  17. public:
  18.     int findMaximumXOR(vector<int>& nums) {
  19.        
  20.                
  21.         Trie* root  =  new Trie();
  22.        
  23.         for(int num : nums)
  24.         {
  25.             insert(num, root);
  26.         }
  27.        
  28.         int res = 0;
  29.         for( int i=0; i<(int)nums.size(); i++ )
  30.         {
  31.             int num = nums[i];
  32.             Trie* node = root;
  33.             int ans = 0;
  34.            
  35.             for(int j=31; j>=0; j-- )
  36.             {
  37.                 int bit = (num >> j) & 1; // we need to extract one bit so can't do things like (1<<i) &num
  38.                
  39.                 if( node->bit[!bit])
  40.                 {
  41.                     ans += (1<<j);
  42.                     node = node->bit[!bit];
  43.                 }
  44.                 else{
  45.                     node = node->bit[bit];
  46.                 }
  47.             }
  48.            
  49.             res = max(res, ans);
  50.         }
  51.        
  52.         return res;
  53.     }
  54.    
  55.     void insert(int num, Trie* root)
  56.     {
  57.         Trie* node = root;
  58.        
  59.         for(int i=31; i>=0;i--)
  60.         {
  61.             int bit = (num >> i)&1;
  62.             if( node->bit[bit] == NULL )
  63.             {
  64.                 node->bit[bit] = new Trie();
  65.             }
  66.            
  67.             node = node->bit[bit];
  68.         }
  69.        
  70.         node->leaf = true;
  71.     }
  72. };
Add Comment
Please, Sign In to add comment