/
421. Maximum XOR of Two Numbers in an Array.cpp
82 lines (64 loc) · 1.45 KB
/
421. Maximum XOR of Two Numbers in an Array.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/
class TrieNode
{
public:
TrieNode *children[2];
TrieNode()
{
children[0] = nullptr;
children[1] = nullptr;
}
};
class Trie
{
private:
TrieNode *root;
public:
Trie()
{
root = new TrieNode();
}
void insert(int &number)
{
TrieNode *current = root;
for (int i = 31; i >= 0; i--)
{
int bit = (number >> i) & 1;
if (current->children[bit] == nullptr)
current->children[bit] = new TrieNode();
current = current->children[bit];
}
}
int getMax(int &number)
{
int result = 0;
TrieNode *current = root;
for (int i = 31; i >= 0; i--)
{
int bit = (number >> i) & 1;
int required = 1 - bit;
if (current->children[required] != nullptr)
{
result = (result | (1 << i));
current = current->children[required];
}
else
current = current->children[bit];
}
return result;
}
};
class Solution
{
public:
int findMaximumXOR(vector<int> &nums)
{
int result = INT_MIN;
Trie *trie = new Trie();
for (int &num : nums)
trie->insert(num);
for (int &num : nums)
result = max(result, trie->getMax(num));
return result;
}
};