forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0421.cpp
More file actions
executable file
·56 lines (50 loc) · 1023 Bytes
/
LC0421.cpp
File metadata and controls
executable file
·56 lines (50 loc) · 1023 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/
Time: O(n • 32)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class TrieNode {
public:
vector<TrieNode*> children;
TrieNode() : children(2) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() : root(new TrieNode()) {}
void insert(int num) {
TrieNode* node = root;
for (int i = 31; i >= 0; i--) {
int b = (num >> i) & 1;
if (!node->children[b])
node->children[b] = new TrieNode();
node = node->children[b];
}
}
int match(int num) {
int best = 0;
TrieNode* node = root;
for (int i = 31; i >= 0; i--) {
int b = (num >> i) & 1;
if (!node->children[b])
b ^= 1;
best ^= b << i;
node = node->children[b];
}
return best;
}
};
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
Trie trie;
int max_x = 0;
for (int& x: nums)
trie.insert(x);
for (int& x: nums)
max_x = max(x ^ trie.match(~x), max_x);
return max_x;
}
};