算法二十天
第七天
寻找两个正序数组的中位数
给定两个数组求合并后其中位数。要求时间复杂度为log(m+n);
这道题就体现了基础的重要性,在写二分归并排序时写过合并这一函数,看到题目立马就反应过来:
#include<bits/stdc++.h>
using namespace std;
vector<int> HeBing(vector<int> &a,vector<int> &b)
{
vector<int> temp;
int i=0,j=0;
while(i<a.size()&&j<b.size())
{
if(a[i]>=b[j])
{
temp.push_back(b[j]);
j++;
}
else
{
temp.push_back(a[i]);
i++;
}
}
while(i<a.size())
{
temp.push_back(a[i]);
i++;
}
while(j<b.size())
{
temp.push_back(b[j]);
j++;
}
return temp;
}
double Mid(vector<int> &temp)
{
if(1&temp.size())//判断奇数还是偶数个
return temp[temp.size()/2];
else
return (double)(temp[temp.size()/2]+temp[temp.size()/2-1])/2;
}
int main()
{
vector<int> a={1,2};
vector<int> b={3,4};
vector<int> temp=HeBing(a,b);
printf("%0.5f",Mid(temp));
}
并不符合题目要求的时间复杂度,明天再写