[leetcode]421. Maximum XOR of Two Numbers in an Array

421. Maximum XOR of Two Numbers in an Array

Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ ij < n.

Could you do this in O(n) runtime?

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.

思路一:

利用a ^ b = c,而a ^ b ^ b = a, 则 c ^ b = a.


    int findMaximumXOR(vector& nums) {
        if( nums.size() < 2 ) return 0;
        int maxNum = 0;
        int flag = 0;
        
        for( int i = 31; i >= 0; --i )
        {//从最大值maxNum最高位到最低位开始确定
            set hash;
            
            flag |= (1<


思路二:

Tire树,利用nums中的数构建tire树,然后依次查找数组nums中数的异或最大值

    struct Node{
        Node * next[2];
        Node()
        {
            next[0] = nullptr;
            next[1] = nullptr;
        }
    };
     
    void buildTireTree(Node* root, int x)
    {
        for( int i = 31; i >= 0; --i )
        {
            int flag =  ( x & (1<next[flag] == nullptr )
            {
                root->next[flag] = new Node();
            }
            root = root->next[flag];
        }
    }
    
    int findMaxXorInTire(Node* root, int x)
    {
        int result = 0;
        
        for( int i = 31; i >= 0; --i )
        {
 
            int flag = ( x & ( 1<next[flag] != nullptr )
            {
                result |= (1<next[flag];
            }
            else
                root = root->next[1-flag];
        }
        return result;
    }
    
public:
    int findMaximumXOR(vector& nums) {
       if( nums.size() < 2 ) return 0;
       Node head;
       for( int x: nums )
       {
           buildTireTree( &head, x );
       }
       
       int maxNum = 0;//INT_MIN;
       for( int x: nums )
       {
           int m = findMaxXorInTire( &head, x );
           maxNum = max( maxNum, m );
       }
       return maxNum;
       
    }




你可能感兴趣的:(c++,leetcode)