A1029 Median (25) Two points

本文介绍了解决数组中位数查找问题的两种不同算法。第一种算法使用了排序方法,通过将两个数组合并并排序,然后找到中间的元素作为中位数。第二种算法采用了双指针技术,在不进行完整排序的情况下找到中位数,这种方法更接近最优解,适用于大数据集。文章通过具体的代码示例展示了这两种算法的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先给一种解法(感觉是因为这题时间限制没有那么大,所以这种解法也可以,但是还是要学会最优解)

#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]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值