-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_STOII_0067_findMaximumXOR.cc
96 lines (93 loc) · 1.56 KB
/
Problem_STOII_0067_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
#include <iostream>
#include <vector>
using namespace std;
// seem as leetcode 0421
// https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array/
// see at Problem_0421_findMaximumXOR.cc
class Solution
{
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 search(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)
{
x = 2 * x + 1;
cur = cur->right;
}
else
{
x = 2 * x;
cur = cur->left;
}
}
else
{
if (cur->left)
{
x = 2 * x + 1;
cur = cur->left;
}
else
{
x = 2 * x;
cur = cur->right;
}
}
}
return x;
}
public:
int findMaximumXOR(vector<int> &nums)
{
int x = 0;
for (int i = 1; i < nums.size(); i++)
{
add(nums[i - 1]);
x = std::max(x, search(nums[i]));
}
return x;
}
};