先给一种解法(感觉是因为这题时间限制没有那么大,所以这种解法也可以,但是还是要学会最优解)
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1000100;
int n,m,a[maxn];
int main()
{
scanf("%d",&n);
for (int i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for (int i=n;i<m+n;i++)
scanf("%d",&a[i]);
sort(a,a+n+m);
n=(n+m-1)/2;
printf("%d",a[n]);
}
Two points解法
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1000010;
const int inf=0x7fffffff;
int s1[maxn],s2[maxn];
int main()
{
int n,m,i,j;
cin>>n;
for (i=0;i<n;i++)
scanf("%d",&s1[i]);
cin>>m;
for ( i=0;i<m;i++)
scanf("%d",&s2[i]);
int mid=(n+m-1)/2;
int count =0;
s1[n]=inf;
s2[m]=inf;
i=0,j=0;
while (count<mid)
{
if (s1[i]<s2[j])i++;
else j++;
count++;
}
if (s1[i]<s2[j])
printf("%d",s1[i]);
else
printf("%d",s1[j]);
}
本文介绍了解决数组中位数查找问题的两种不同算法。第一种算法使用了排序方法,通过将两个数组合并并排序,然后找到中间的元素作为中位数。第二种算法采用了双指针技术,在不进行完整排序的情况下找到中位数,这种方法更接近最优解,适用于大数据集。文章通过具体的代码示例展示了这两种算法的实现。
2235

被折叠的 条评论
为什么被折叠?



