LeetCode——Median of Two Sorted Arrays
leetcode上第四题:
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)).
题目翻译:
给定两个已经排序过的数组,求这两个数组中的中位数,要求时间复杂度为O(log (m+n)).
<span style="font-size:14px;">#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int n = nums1.size();
int m = nums2.size();
vector<int> num3;
num3.insert(num3.end(),nums1.begin(),nums1.end());
num3.insert(num3.end(),nums2.begin(),nums2.end());
sort(num3.begin(),num3.end());
int k = n+m;
double target = (double) (k%2?num3[k/2]:(num3[k/2]+num3[k/2-1])/2.0);
return target;
}
int main()
{
int a[] = {3,7,8};
int b[] = {2,6,9};
vector<int> s1(a,a+3);
vector<int> s2(b,b+3);
double tar = findMedianSortedArrays(s1,s2);
cout<<tar<<endl;
return 0;
}</span>
其实此方法在最坏的情况下是O (n log n),但是题目中说过已经两个数组都是已经排过序的,所以可以勉强达到leetcode平台的要求吧(个人感觉检查不够严格)
已经想到了一种时间复杂度为O(log (m+n))的算法:我们可以算出中位数元素在所有元素中是第几个记为n,因为两个数组是已经排好序的,所以不断的比较两个数组的元素,直到数量达到n,记录该元素(对于奇数个就可以返回值了,对于偶数个需要再求出下一个)。