PAT Advanced1029 Median

版权声明:个人学习笔记记录 https://blog.csdn.net/Ratina/article/details/85633769

一道卡了好久令人心情复杂的题。。。。

链接:PAT Advanced1029

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×10​5) 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


题意:给定长度为n,m的两个递增序列,求 按非递减合并后 的序列的中间数。



思路很简单,就是两个序列挨个地对比,找到第 (n+m) / 2个数。但是,直接这样操作第8个测试点会爆内存…

看了别人的方法,使用了队列,这样处理起来不仅方便,而且可以在读入第二个序列的同时进行判断、出队列,达到释放空间、释放内存的目的。
再者,将INT_MAX放在两队列末尾,这样就不用特意去处理一个队列已空的情况的了。


以下代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{   
	queue<int> a,b;
	int n,m,M,i,t,cnt=0;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&t);
		a.push(t);
	}
	a.push(INT_MAX);
	scanf("%d",&m);
	M=(n+m-1)/2;
	for(i=0;i<m;i++)
	{
		scanf("%d",&t);
		b.push(t);
		if(cnt==M)     //该语句要放在b.push(t)之后,b.pop()之前
		{
            printf("%d", min(a.front(), b.front()));
            return 0;
        }
        if(a.front()<b.front())   
            a.pop();
        else                        
            b.pop();
        cnt++;
	}
	b.push(INT_MAX);
	while(cnt<M)
	{
		if(a.front()<b.front())
			a.pop();
		else
			b.pop();
		cnt++;
	}
	printf("%d",min(a.front(),b.front()));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Ratina/article/details/85633769
今日推荐