1029 Median (25 point(s))
Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1 = { 11, 12, 13, 14 } is 12, and the median of S2 = { 9, 10, 15, 16, 17 } is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
Given two increasing sequences of integers, you are asked to find their median.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤2×105) is the size of that sequence. Then N integers follow, separated by a space. It is guaranteed that all the integers are in the range of long int.
Output Specification:
For each test case you should output the median of the two given sequences in a line.
Sample Input:
4 11 12 13 14
5 9 10 15 16 17
Sample Output:
13
思路:
1.原本思路:开两个数组,然后采用归并排序的方式查找median元素(设置两个游标i,j)。结果:内存超限(22)。
2.正解思路:只开一个数组,然后对于每一个新输入的元素进行判断。
3.核心:归并排序
(1)注意判断median元素(即cnt==0时结束);
(2)注意有可能第二个序列输入完以后,还没有找到median(即在数组a[]还没遍历的部分)。
#include<iostream>
using namespace std;
const int MAX = 200007;
int a[MAX];
int main(void)
{
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
scanf("%d",&m);
int temp;
int index=0;
int cnt = (n+m+1)/2;//目标计数
int res;
for(int i=0;i<m;i++){
scanf("%d",&temp);
while(temp>a[index]&&index<n&&cnt){//如果新输入的数大于当前index指向的数
index++;cnt--;//index移动,计数减少1
}
if(cnt==0){//如果此时计数结束,则说明中位数已经产生
res=a[--index];//注意必须要回溯1个元素
break;
}
cnt--;//没有到达中位数位置(即cnt不是0),则计数再减少1个(即temp)
if(cnt==0){//如果此时计数结束,原理同上
res=temp;
break;
}
}
if(cnt){//如果所有的数输入完毕以后,还没有出现中位数,说明中位数在序列a[]中
while(cnt--){
index++;
}
res=a[--index];
//res=a[index+cnt-1];
}
printf("%d\n",res);
return 0;
}
附:原本思路代码
#include<iostream>
using namespace std;
const int MAX = 200007;
int a[MAX],b[MAX];
int main(void)
{
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
scanf("%d",&m);
for(int i=0;i<m;i++) scanf("%d",&b[i]);
int count=0,i=0,j=0;
int pre;
while(count<(n+m+1)/2){
if(i<n&&j<m){
if(a[i]<b[j]){
pre = a[i];
i++;
}
else{
pre = b[j];
j++;
}
}
else if(i>=n){
pre = b[j];
j++;
}
else{
pre = a[i];
i++;
}
count++;
}
printf("%d\n",pre);
return 0;
}
https://pintia.cn/problem-sets/994805342720868352/problems/994805466364755968