-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0421_findMaximumXOR.cc
151 lines (141 loc) · 2.4 KB
/
Problem_0421_findMaximumXOR.cc
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
#include <unordered_set>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int findMaximumXOR1(vector<int> &nums)
{
int ans = 0;
const int mask = 30;
for (int i = 30; i >= 0; i--)
{
unordered_set<int> set;
for (auto &num : nums)
{
set.emplace(num >> i);
}
int next = 2 * ans + 1;
bool found = false;
for (auto &num : nums)
{
if (set.count(next ^ (num >> i)))
{
found = true;
break;
}
}
if (found)
{
ans = next;
}
else
{
ans = next - 1;
}
}
return ans;
}
class Node
{
public:
Node *left;
Node *right;
Node()
{
left = nullptr;
right = nullptr;
}
};
Node *root = new Node();
const int mask = 30;
void add(int num)
{
Node *cur = root;
for (int i = mask; i >= 0; i--)
{
int bit = (num >> i) & 1;
if (bit == 0)
{
if (!cur->left)
{
cur->left = new Node();
}
cur = cur->left;
}
else
{
if (!cur->right)
{
cur->right = new Node();
}
cur = cur->right;
}
}
}
int check(int num)
{
Node *cur = root;
int x = 0;
for (int i = mask; i >= 0; i--)
{
int bit = (num >> i) & 1;
if (bit == 0)
{
if (cur->right)
{
cur = cur->right;
x = x * 2 + 1;
}
else
{
cur = cur->left;
x = x * 2;
}
}
else
{
if (cur->left)
{
cur = cur->left;
x = x * 2 + 1;
}
else
{
cur = cur->right;
x = x * 2;
}
}
}
return x;
}
int findMaximumXOR2(vector<int> &nums)
{
int n = nums.size();
int x = 0;
for (int i = 1; i < n; i++)
{
add(nums[i - 1]);
x = std::max(x, check(nums[i]));
}
return x;
}
};
void test()
{
Solution s;
vector<int> n1 = {3, 10, 5, 25, 2, 8};
vector<int> n2 = {14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70};
EXPECT_EQ_INT(28, s.findMaximumXOR1(n1));
EXPECT_EQ_INT(127, s.findMaximumXOR1(n2));
EXPECT_EQ_INT(28, s.findMaximumXOR2(n1));
EXPECT_EQ_INT(127, s.findMaximumXOR2(n2));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}