-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfindMaximumXOR.cpp
More file actions
56 lines (52 loc) · 1.59 KB
/
findMaximumXOR.cpp
File metadata and controls
56 lines (52 loc) · 1.59 KB
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
struct TrieNode{
int val;
TrieNode *left;
TrieNode *right;
TrieNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
TrieNode* root = new TrieNode(0);
//build tree
TrieNode* curNode = root;
for(int i = 0; i < nums.size(); i++){
for(int j = 31; j >= 0; j--) {
int tmp = nums[i] & (1 << j);
if(tmp == 0){
if(!curNode->right){
curNode->right = new TrieNode(0);
}
curNode = curNode->right;
}else{
if(!curNode->left){
curNode->left = new TrieNode(1);
}
curNode = curNode->left;
}
}
curNode = root;
}
//find the max
int max = 0;
for(int i = 0; i < nums.size(); i++){
int res = 0;
for(int j = 31; j >= 0; j--){
int tmp = nums[i] & (1 << j);
if(curNode->left && curNode->right){
if(tmp == 0){
curNode = curNode->left;
}else {
curNode = curNode->right;
}
}else {
curNode = curNode->left == NULL ? curNode->right:curNode->left;
}
res += tmp ^ (curNode->val << j);
}
curNode = root;
max = max > res?max:res;
}
return max;
}
};