[LeetCode] Maximum XOR of Two Numbers in an Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
struct Trie {
Trie* next[2];
Trie() {
memset(next, 0, sizeof(next));
}
};
class Solution {
Trie* trie;
public:
int findMaximumXOR(vector<int>& nums) {
trie = new Trie();
int res = 0;
for(auto n : nums) insert(n);
for(auto n : nums) res = max(res, search(n));
return res;
}
void insert(int n) {
Trie* node = trie;
for(int i = 31; i >= 0; i--) {
int bit = (n>>i) & 1;
if(!node->next[bit]) node->next[bit] = new Trie();
node = node->next[bit];
}
}
int search(int n) {
Trie* node = trie;
int res = 0;
for(int i = 31; i >= 0; i--) {
int bit = (n>>i) & 1;
if(node->next[!bit]) {
res += (1<<i);
node = node->next[!bit];
} else node = node->next[bit];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/maximum-xor-of-two-numbers-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.