-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_421_MaxXORofTwoNumInArray.cpp
61 lines (55 loc) · 1.29 KB
/
LC_421_MaxXORofTwoNumInArray.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
/*
https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/
421. Maximum XOR of Two Numbers in an Array
*/
struct TrieNode{
TrieNode* children[26];
bool isLeaf;
};
class Solution {
public:
TrieNode* root;
void insert(int num)
{
TrieNode* ptr = root;
for(int i=31; i>=0; i--)
{
int bit =(num>>i)&1;
if(ptr->children[bit] == nullptr)
ptr->children[bit] = new TrieNode();
ptr = ptr->children[bit];
}
}
int findxor(int num)
{
trace1(num);
int xr=0;
TrieNode* ptr = root;
for(int i=31; i>=0; i--)
{
int bit =(num>>i)&1;
if(ptr->children[!bit])
{
xr |= 1<<i;
ptr = ptr->children[!bit];
}
else{
ptr = ptr->children[bit];
}
// cout<<bit<<"->"<<bitset<5>(xr)<<" ";
}
// cout<<num<<" "<<xr<<endl;
return xr;
}
int findMaximumXOR(vector<int>& nums) {
root = new TrieNode();
int ans = 0;
for(const int &x: nums)
insert(x);
for(const int &x: nums)
{
ans = max(ans, findxor(x));
}
return ans;
}
};