-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path080_Maximum XOR With an Element From Array.cpp
96 lines (73 loc) · 1.68 KB
/
080_Maximum XOR With an Element From 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
96
// Time Complexity -> O(n * 32)
// Space Complexity -> O(n * 32)
#include <bits/stdc++.h>
class Node
{
private:
Node* links[2] = {nullptr};
public:
bool containsKey(int bit)
{
return links[bit] != nullptr;
}
void put(int bit, Node* node)
{
links[bit] = node;
}
Node* get(int bit)
{
return links[bit];
}
};
class BitTrie{
private:
Node* root;
public:
BitTrie()
{
root = new Node();
}
void insert(int num)
{
Node *temp = root;
for(int i = 31; i >= 0; --i)
{
int bit = (num >> i) & 1;
if(!temp->containsKey(bit))
{
temp->put(bit, new Node());
}
temp = temp->get(bit);
}
}
int findMax(int num)
{
Node* temp = root;
int maxNum = 0;
for(int i = 31; i >= 0; --i)
{
int bit = (num >> i) & 1;
if(temp->containsKey(1-bit))
{
maxNum |= (1 << i);
temp = temp->get(1-bit);
}
else
temp = temp->get(bit);
}
return maxNum;
}
};
int maximumXor(vector<int> A)
{
// Write your code here.
BitTrie *trie = new BitTrie();
for(auto itr : A)
trie->insert(itr);
int maxNum = 0;
for(auto itr : A)
{
maxNum = max(maxNum, trie->findMax(itr));
}
return maxNum;
}