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)).
You may assume nums1 and nums2 cannot be both empty.
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
思路:
不知道这道题为什么是Hard难度,直接把两个vector融合(merge)到一个新的vector里,然后取新vector的中位数即可。值得注意的是,vector的merge方法,两个vector必须是排好序的,默认升序,而且新的vector的大小要够用。AC代码如下:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int len1 = nums1.size(), len2 = nums2.size();
if (len1 == 0)
return len2 % 2 == 0 ? (nums2[len2 / 2 - 1] + nums2[len2 / 2]) / 2.0 : nums2[len2 / 2];
if (len2 == 0)
return len1 % 2 == 0 ? (nums1[len1 / 2 - 1] + nums1[len1 / 2]) / 2.0 : nums1[len1 / 2];
vector<int> u(len1 + len2, 0); // union
merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), u.begin());
int u_len = u.size();
if (u_len % 2 == 0) // 偶数
return (double)((u[u_len / 2 - 1] + u[u_len / 2]) / 2.0); // 比如一共4个数,返回1,2位置平均值
return (double)(u[u.size() / 2]);
}