Skip to content

Commit 2ec9f88

Browse files
author
Aditya Mukherjee
committed
Added alternative solution using merge sort technique
1 parent bc4b68c commit 2ec9f88

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Approach:
3+
let nums1 = [1, 3, 4, 7, 10, 12], nums2 = [2, 3, 6, 15]
4+
5+
In order to find the median, we need a single sorted array. So a naive approach is that, just merge the 2 sorted arrays and find the median of that array.
6+
This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2)
7+
*/
8+
9+
# include <bits/stdc++.h>
10+
11+
class Solution {
12+
std::vector<int> merge(std::vector<int>& nums1, std::vector<int>& nums2){
13+
int n1 = nums1.size();
14+
int n2 = nums2.size();
15+
16+
int i=0, j=0;
17+
18+
std::vector<int> res;
19+
while(i < n1 and j < n2){
20+
if(nums1[i] < nums2[j]){
21+
res.push_back(nums1[i]);
22+
i++;
23+
} else {
24+
res.push_back(nums2[j]);
25+
j++;
26+
}
27+
}
28+
29+
while(i < n1){
30+
res.push_back(nums1[i]);
31+
i++;
32+
}
33+
34+
while(j < n2){
35+
res.push_back(nums2[j]);
36+
j++;
37+
}
38+
39+
return res;
40+
}
41+
public:
42+
double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2) {
43+
std::vector<int> sortedarr = merge(nums1, nums2);
44+
45+
if(sortedarr.size() % 2 == 0){
46+
return (sortedarr[sortedarr.size()/2] + sortedarr[sortedarr.size()/2 - 1])/2.0;
47+
} else {
48+
return (double)sortedarr[sortedarr.size()/2];
49+
}
50+
}
51+
};
52+
53+
int main(int argc, char const* argv[]) {
54+
int n;
55+
56+
std::cin >> n;
57+
std::vector<int> arr1(n, 0);
58+
for (int i = 0;i < n;i++) {
59+
std::cin >> arr1[i];
60+
}
61+
62+
std::cin >> n;
63+
std::vector<int> arr2(n, 0);
64+
for (int i = 0;i < n;i++) {
65+
std::cin >> arr2[i];
66+
}
67+
68+
Solution sol = Solution();
69+
double res = sol.findMedianSortedArrays(arr1, arr2);
70+
71+
std::cout << res << "\n";
72+
return 0;
73+
}

0 commit comments

Comments
 (0)