PAT A1029 Median 中位数【two pointers】

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.

给出一个N个整数的递增序列S,中位数是位于中间位置的数字。比如说,S1={11,12,13,14}的中位数是12,S2={9,10,15,16,17}的中位数是15.两个序列的中位数是两个序列所有元素以非递减顺序排列后的中位数,比如S1和S2的中位数是13 {9,10,11,12,13,14,15,16,17}

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.

每一个测试样例占两行,每一行给出了一个序列信息。每一个序列第一个正整数N(≤2×10^5)是这个序列的大小,之后有N个数用空格隔开。保证所有的整数都在long int范围内

Output Specification:

For each test case you should output the median of the two given sequences in a line.

输出两个序列的中位数


#include <iostream>
const int maxn=1000010;
const int INF=0x7fffffff;
int s1[maxn],s2;
int main(){
	int num1,num2;
	scanf("%d",&num1);
	for(int i=0;i<num1;i++)
		scanf("%d",&s1[i]);
	scanf("%d",&num2);
		scanf("%d",&s2);
	s1[num1]=INF;
	for(int i=0,j=0;i<=num1&&j<=num2;){
		if(s1[i]<s2){
			if(i+j+1==(num1+num2+1)/2){
				printf("%d",s1[i]);
				break;
			}
			i++;
		}else{
			if(i+j+1==(num1+num2+1)/2){
				printf("%d",s2);
				break;
			}
			j++;
			if(j<num2)
			scanf("%d",&s2);
			else if(j==num2) s2=INF;
		}
	}
	return 0;
}

令两个序列最后都添加一个很大的数INF(本题为int类型最大值),这样就可以在其中一个序列已经扫描完但还没找到中位数的情况下解决访问越界问题。

第一个序列全部读入数组,第二个序列一个数一个数读,解决内存受限问题。

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86668487