Description:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
题目分析:按照归并排序的思路,先归并,再计算中间值。
Solution:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
vector<int> array = merge(nums1, nums2);
return ((double)(array[(m+n-1)/2]+array[(m+n)/2]))/2;
}
vector<int> merge(vector<int> A, vector<int> B)
{
vector<int> ret;
int m = A.size();
int n = B.size();
int i = 0;
int j = 0;
while(i < m && j < n)
{
if(A[i] <= B[j])
{
ret.push_back(A[i]);
i ++;
}
else
{
ret.push_back(B[j]);
j ++;
}
}
if(i == m)
{
while(j < n)
{
ret.push_back(B[j]);
j ++;
}
}
if(j == n)
{
while(i < m)
{
ret.push_back(A[i]);
i ++;
}
}
return ret;
}
};