-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
findMaximumXOR.cpp
76 lines (63 loc) · 1.57 KB
/
findMaximumXOR.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
class Trie {
public:
Trie() {
next[0] = next[1] = nullptr;
}
~Trie() {
if (next[0]) delete next[0];
if (next[1]) delete next[1];
}
void insert(int n) {
Trie* cur = this;
for (int i = 31; i >= 0; --i) {
if (n & (1 << i)) {
if (!cur->next[1]) {
cur->next[1] = new Trie();
}
cur = cur->next[1];
} else {
if (!cur->next[0]) {
cur->next[0] = new Trie();
}
cur = cur->next[0];
}
}
cur->val = n;
}
int findOpposite(int n) {
Trie* cur = this;
for (int i = 31; i >= 0; --i) {
if (n & (1 << i)) {
if (cur->next[0]) {
cur = cur->next[0];
} else {
cur = cur->next[1];
}
} else {
if (cur->next[1]) {
cur = cur->next[1];
} else {
cur = cur->next[0];
}
}
}
return cur->val;
}
private:
int val;
Trie* next[2];
};
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
int ans = 0;
Trie root;
for (auto n : nums) {
root.insert(n);
}
for (auto n : nums) {
ans = max(ans, n ^ root.findOpposite(n));
}
return ans;
}
};