-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
45 lines (42 loc) · 1018 Bytes
/
Solution.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
class Trie {
public:
vector<Trie*> children;
string v;
Trie()
: children(2) {}
void insert(int x) {
Trie* node = this;
for (int i = 30; ~i; --i) {
int v = (x >> i) & 1;
if (!node->children[v]) node->children[v] = new Trie();
node = node->children[v];
}
}
int search(int x) {
Trie* node = this;
int res = 0;
for (int i = 30; ~i; --i) {
int v = (x >> i) & 1;
if (node->children[v ^ 1]) {
res = res << 1 | 1;
node = node->children[v ^ 1];
} else {
res <<= 1;
node = node->children[v];
}
}
return res;
}
};
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
Trie* trie = new Trie();
int ans = 0;
for (int v : nums) {
trie->insert(v);
ans = max(ans, trie->search(v));
}
return ans;
}
};