421. Maximum XOR of Two Numbers in an Array

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

Follow up: Could you do this in O(n) runtime?

 

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 = [0]
Output: 0

Example 3:

Input: nums = [2,4]
Output: 6

Example 4:

Input: nums = [8,10,2]
Output: 10

Example 5:

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

 

Constraints:

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

Rust Solution

struct Solution;
use std::collections::HashSet;

impl Solution {
    fn find_maximum_xor(nums: Vec<i32>) -> i32 {
        let mut max = 0;
        let mut mask = 0;
        for i in (0..30).rev() {
            mask |= 1 << i;
            let mut hs: HashSet<i32> = HashSet::new();
            for &x in &nums {
                hs.insert(x & mask);
            }
            let tmp = max | (1 << i);
            for &x in &hs {
                if hs.contains(&(tmp ^ x)) {
                    max = tmp;
                    break;
                }
            }
        }
        max
    }
}

#[test]
fn test() {
    let nums = vec![3, 10, 5, 25, 2, 8];
    let res = 28;
    assert_eq!(Solution::find_maximum_xor(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.