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)). You may assume nums1 and nums2 cannot be both empty.
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数,并且
要求算法的时间复杂度为 O(log(m + n))
。你可以假设 nums1 和 nums2 不会同时为空。
Example
Input:
nums1 = [1, 3]
nums2 = [2]
Output:
The median is 2.0
Input:
nums1 = [1, 2]
nums2 = [3, 4]
Output:
The median is (2 + 3)/2 = 2.5
My Solution
直接将一个vector插到另一个后面,再排序取中值(全程调用系统函数。。)。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
for (size_t i = 0; i < nums1.size(); i++)
nums2.push_back(nums1[i]);
sort(nums2.begin(), nums2.end());
if (nums2.size() % 2 == 0)
return (nums2[nums2.size() / 2] + nums2[nums2.size() / 2 - 1]) / 2.0;
else
return nums2[(nums2.size() - 1) / 2] * 1.0;
}
int main(void)
{
vector<int> v1 = {4, 5, 1};
vector<int> v2 = {1, 2};
cout << findMedianSortedArrays(v1, v2) << endl;
}