码迷,mamicode.com
首页 > 其他好文 > 详细

PAT A1029 Median (25 分)

时间:2021-02-17 14:40:27      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:代码   amp   namespace   mes   example   一个   实现   出现   pre   

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

实现思路:

这是two pointers双指针的做法,目的在于在两个有序数组中找到中位数,因为题目说单个数据不超过long int,则一个元素最大可占8B,若采用数组存下两个序列则会出现内存超限。所以采用双指针做法,保存第一个有序序列,而第二个有序序列不进行保存,换成是一个指针指向第一个序列,在接受第二个序列数值时进行比较对比,直到找到中间位置(n+m+1)/2的那个数为止。

AC代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN=200010;
int sq[MAXN];

int main() {
	int n,val,m;
	cin>>n;
	sq[n]=0x7fffffff;
	for(int i=0; i<n; i++) scanf("%d",&sq[i]);
	cin>>m;
	int midPos=(n+m-1)/2,cnt=-1,index=0;
	for(int i=0; i<m; i++) {
		scanf("%d",&val);
		while(sq[index]<val) {
			cnt++;
			if(cnt==midPos) cout<<sq[index];
			index++;
		}
		cnt++;
		if(cnt==midPos) cout<<val;
	}
	//s2都比较完毕的情况
	while(index<n) {
		cnt++;
		if(cnt==midPos) {
			cout<<sq[index];
		}
		index++;
	}
	return 0;
}

PAT A1029 Median (25 分)

标签:代码   amp   namespace   mes   example   一个   实现   出现   pre   

原文地址:https://www.cnblogs.com/coderJ-one/p/14402256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!