421. Maximum XOR of Two Numbers in an Array

Medium (Trung bình) C++ 🔗 Xem trên LeetCode

📋 Đề Bài

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

 

Example 1:

Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.

Example 2:

Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127

 

Constraints:

  • 1 <= nums.length <= 2 * 105
  • 0 <= nums[i] <= 231 - 1

🧠 Thuật Toán & Kỹ Thuật

Bit Manipulation (Thao tác bit)Union Find (Tập hợp rời rạc)Trie (Cây tiền tố)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0421-maximum-xor-of-two-numbers-in-an-array.cpp
struct TrieNode {
    TrieNode *children[2];
    
    TrieNode() {
        for (int i = 0; i < 2; ++i) {
            children[i] = nullptr;
        }
    }
};

class Trie {
private:
    TrieNode *root;
    
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(int num) {
        TrieNode *curr = root;
        for (int i = 31; i >= 0; --i) {
            int bit = (num >> i) & 1;
            if (curr->children[bit] == nullptr) {
                curr->children[bit] = new TrieNode();
            }
            curr = curr->children[bit];
        }
    }
    
    int find(int num) {
        TrieNode *curr = root;
        int ans = 0;
        for (int i = 31; i >= 0; --i) {
            int bit = (num >> i) & 1;
            if (curr->children[1 - bit]) {
                curr = curr->children[1 - bit];
                ans |= (1 << i);
            }
            else {
                curr = curr->children[bit];
            }
        }
        return ans;
    }
};

class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        Trie trie;
        for (int num : nums) {
            trie.insert(num);
        }
        int ans = 0;
        for (int num : nums) {
            ans = max(ans, trie.find(num));
        }
        return ans;
    }
};