1029 Median (25分)【序列合并】

1029 Median (25分)

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

解题思路:

本题给出两个已经递增的序列s1和s2,长度分别为N和M,求将它们合并成为一个新的递增序列后的中位数(个数为偶数个时取左半部分的最后一个数)。 

我们可以利用i和j两个下标来完成类似于归并排序一样的合并,不过这里我们可以做一些小小的改进:

1.我们并不需要用一个额外的数组来存储合并后的结果,只需要找到第mid(mid=(n+m-1)/2)大的数,因此我们也并不需要遍历完所有数。

2.注意当其中某个数组已经遍历完,但是还没有找到第mid大的数,为了能继续比较下去,我们需要将s1和s2数组的末尾两个值设置为10^9

#include<iostream>
#include<cstdio>
using namespace std;
#define MAXN 1000010
int s1[MAXN], s2[MAXN];     //s1和s2序列

int main()
{
	int n, m;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &s1[i]);    //输入第一个序列
	}
	cin >> m;
	for (int i = 0; i < m; i++)
	{
		scanf("%d", &s2[i]);   //输入第二个序列
	}
	s1[n] = s2[m] = 1e9;
	int mid = (n + m - 1) / 2;
	int i = 0, j = 0, count = 0;
	while (count < mid)
	{
		if (s1[i] < s2[j])
			i++;
		else j++;
		count++;
	}
	if (s1[i] < s2[j])
		printf("%d\n", s1[i]);
	else printf("%d\n", s2[j]);
	return 0;
}
发布了119 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lovecyr/article/details/105447476