-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4. Median of Two Sorted Arrays
43 lines (39 loc) · 1.15 KB
/
4. Median of Two Sorted Arrays
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
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> merged;//(nums1.size()+nums2.size());
int i = 0,j = 0;
// while(i < nums1.size() && j < nums2.size()){
if (nums1.empty() ){
merged = nums2;
}else if(nums2.empty()){
merged = nums1;
}else{
do{
if (nums1[i] <= nums2[j]){
merged.push_back(nums1[i]);
i++;
}else{
merged.push_back(nums2[j]);
j++;
}
}
while(i < nums1.size() && j < nums2.size());
while(i < nums1.size()){
merged.push_back(nums1[i]);
i++;
}
while(j < nums2.size()){
merged.push_back(nums2[j]);
j++;
}
}
//for (auto i:merged){cout<<i<<" "<<merged.size();}
if (merged.size() % 2 == 1){
return merged[merged.size()/2];
}else{
double s = (merged[merged.size()/2]+merged[merged.size()/2-1])*0.5;
return s;
}
}
};