zoukankan      html  css  js  c++  java
  • 421. Maximum XOR of Two Numbers in an Array——本质:利用trie数据结构查找

    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 ≤ i, j < 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.
    
    class Solution(object):
        def findMaximumXOR(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            [3,10,5]
            0x11, 
          0x1010, 
           0x101, 
         0x11001, 
            0x10, 
           0x100
    -------------
    
            """
            root = [None]*2
            for num in nums:
                self.build_trie(root, num)
            ans = 0
            for num in nums:
                ans = max(ans, self.max_xor_of(root, num))
            return ans
            
        def build_trie(self, root, num):
            for i in range(30, -1, -1):
                flag = 1 if (num & (1<<i)) else 0
                if root[flag] is None:
                    root[flag] = [None]*2
                root = root[flag]
        
        def max_xor_of(self, root, num):
            ans = 0
            for i in range(30, -1, -1):
                flag = 0 if (num & (1<<i)) else 1
                if root is None:
                    break
                if root[flag] is not None:
                    ans |= (1<<i)
                    root = root[flag]
                else:
                    root = root[1-flag]
            return ans                    
  • 相关阅读:
    C++——多态性
    C++——继承与派生
    C++——字符串处理
    C++——深拷贝
    C++——浅拷贝
    C++——动态内存分配3
    C++——动态内存分配2-创建对象数组
    C++——动态内存分配1
    C++——指针5
    C++——指针4
  • 原文地址:https://www.cnblogs.com/bonelee/p/6220923.html
Copyright © 2011-2022 走看看