题目描述
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
分析
这道题是找两个排序向量的中位数,还要求了时间复杂度。这道题其实有一个取巧的做法,把这两个向量使用memcpy拷贝到一个更大空间的向量中,然后对向量进行排序,最后判断元素奇偶就可以直接输出中位数了。这个算法的时间复杂度就在于排序。如果使用sort,虽然理论平均时间复杂度比题目要求的高,但是因为之前向量已经是排序过了,所以实际运行时间并不会很长。因为sort并不只是快速排序算法,是由很多排序算法组合到一起实现的。
在实现时,还需要注意判断输入是否为空。另外,对于memcpy函数的输入是void*,也就是需要输入地址。对于数组来说,数组名就是首地址,那么vector的地址是什么呢?vector中有一个函数data,就是用来获取容器的首地址。
AC代码如下:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
vector<int> a(m+n);//新容器
if(m != 0)//判断输入是否为空
{
memcpy(a.data(), nums1.data(), sizeof(int)*m);//内存拷贝
}
if(n != 0)//判断输入是否为空
{
memcpy(a.data()+m, nums2.data(), sizeof(int)*n);//内存拷贝
}
sort(a.begin(), a.end());
if((m + n) % 2 == 0)//偶数
{
return (double)(a[(m+n)/2] + a[(m+n)/2-1])/2;
}
else//奇数
{
return a[(m+n)/2];
}
}
};