forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0421.cpp
More file actions
86 lines (60 loc) · 1.91 KB
/
Copy path0421.cpp
File metadata and controls
86 lines (60 loc) · 1.91 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
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
class Trie{
public:
Trie* left;
Trie* right;
};
Trie* insertNode(Trie* head, int val){
Trie* curr = head;
for(int i = 31; i >= 0; i--){
int bit = (val >> i) & 1;
if(bit == 0){
if(!curr -> left)
curr -> left = new Trie();
curr = curr -> left;
}
else{
if(!curr -> right)
curr -> right = new Trie();
curr = curr -> right;
}
}
return head;
}
class Solution {
public:
int calXor(Trie* head, vector<int>& nums){
int maxVal = INT_MIN;
for(int i = 0; i < nums.size(); i++){
int val = nums[i];
int temp = 0;
Trie* curr = head;
for(int j = 31; j >= 0; j--){
int bit = (val >> j) & 1;;
if(bit == 0){
if(curr -> right){
temp += pow(2, j);
curr = curr -> right;
}
else
curr = curr -> left;
}
else{
if(curr -> left){
temp += pow(2, j);
curr = curr -> left;
}
else
curr = curr -> right;
}
}
maxVal = max(maxVal, temp);
}
return maxVal;
}
int findMaximumXOR(vector<int>& nums) {
Trie* head = new Trie();
for(int i = 0; i < nums.size(); i++)
head = insertNode(head, nums[i]);
return calXor(head, nums);
}
};