Leetcode 421 Solution

This article provides solution to leetcode question 421 (maximum-xor-of-two-numbers-in-an-array)

https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array

Solution

class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        int max_val = 0;
        int mask = 0;

        for (int i = 30; i >= 0; i--)
        {
            mask |= 1 << i;

            set<int> s;
            for (auto num : nums)
                s.insert(num & mask);

            int tmp = max_val | (1 << i);

            for (auto num : s)
            {
                if (s.find(num ^ tmp) != s.end())
                {
                    max_val = tmp;
                    break;
                }
            }
        }

        return max_val;
    }
};