题目
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
思路:
本题,没有时间复杂度的要求,那么使用STL中函数,时间复杂度为(M+n)log(M+N),时间复杂度log(M+N)的解法暂时还没想到一个易于理解的,故之后再补上。。。
代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
nums2.insert(nums2.end(),nums1.begin(),nums1.end());
int size = nums2.size();
sort(nums2.begin(),nums2.end());
if(size%2==0)
return (nums2[size/2-1]+nums2[size/2])/2.0;
else
return nums2[size/2];
}
};