-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-xor-of-two-numbers-in-an-array.cpp
75 lines (70 loc) · 1.4 KB
/
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
//idea: prefix tree
class node {
public:
//child node represent zero
node *zero;
//child node represent one
node *one;
//constructor
node() :
zero(nullptr),
one(nullptr) {
}
node *update(int value) {
if (value == 1) {
if (!one)
one = new node();
return one;
} else {
if (!zero) {
zero = new node();
}
return zero;
}
}
};
class Solution {
public:
int findMaximumXOR(vector<int> &nums) {
root = new node;
//建树
for (auto num:nums)
insert(num);
int result = 0;
//根据xor计算的性质,找到与num xor运算最大的那个前缀
for (auto num:nums)
result = max(findMax(num), result);
return result;
}
private:
int findMax(int num) {
int result = 0;
node *cur = root;
for (int pos = 31; pos >= 0; --pos) {
int digit = (num >> pos) & 1;
if (digit == 1) {
if (cur->zero) {
result = result | (1 << pos);
cur = cur->zero;
} else
cur = cur->one;
} else {
if (cur->one) {
result = result | (1 << pos);
cur = cur->one;
} else
cur = cur->zero;
}
}
return result;
}
void insert(int val) {
node *cur = root;
for (int pos = 31; pos >= 0; --pos) {
int digit = (val >> pos) & 1;
cur = cur->update(digit);
}
}
private:
node *root;
};