-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path421-maximum-xor-of-two-numbers-in-an-array.cpp
executable file
·95 lines (90 loc) · 2.08 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
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* @lc app=leetcode.cn id=421 lang=cpp
*
* [421] 数组中两个数的最大异或值
*/
// @lc code=start
class Solution
{
public:
struct Node
{
Node *one;
Node *zero;
Node() : one(nullptr), zero(nullptr) {}
};
Node *CreateTree(const vector<int> &nums)
{
Node *root = new Node();
for (auto &num : nums)
{
Node *n = root;
for (int i = 30; i >= 0; --i)
{
bool isOne = (num >> i) & 1;
if (isOne)
{
if (!n->one)
{
n->one = new Node();
}
n = n->one;
}
else
{
if (!n->zero)
{
n->zero = new Node();
}
n = n->zero;
}
}
}
return root;
}
int search(Node *root, int num)
{
Node *n = root;
int res = 0;
for (int i = 30; i >= 0; --i)
{
bool isOne = (num >> i) & 1;
if (isOne)
{
if (n->zero)
{
res |= (1 << i);
n = n->zero;
}
else if (n->one)
{
n = n->one;
}
}
else
{
if (n->one)
{
res |= (1 << i);
n = n->one;
}
else if (n->zero)
{
n = n->zero;
}
}
}
return res;
}
int findMaximumXOR(vector<int> &nums)
{
int res = INT_MIN;
Node *root = CreateTree(nums);
for (auto &num : nums)
{
res = max(res, search(root, num));
}
return res;
}
};
// @lc code=end