PAT 真题 | 1029 Median

这道题目通过率非常低, 自己也是花了大半天功夫才AC的. 特别感谢柳婼的Blog, 上面收集了每道PAT真题的题解, 收获很大. 网址放在文章最后面.

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:

1
2
4 11 12 13 14
5 9 10 15 16 17

Sample Output:

1
13

时间限制: 200 ms
内存限制: 1.5 MB
代码长度限制: 16 KB

题目分析

这道题给出两个排好序的串, 求合并后有序串的中位数. 这道题的难点在于内存限制得很小, 无法满足开两个数组储存两个整数串, 只能开一个. 这道题主要的一个坑点是题目说整数全部在long int(8 bytes) 范围内, 实际全部是 int(4 bytes) 范围内. 解题思路是开一个int数组, 先把第一个串存进来. 然后动态读取第二个数组, 在读取的同时进行比较, 模拟归并排序. 最后若读取完毕第一个串还没有读取完毕, 则继续读取第一个串. 全过程位置不断增加, 中间位置 midpos 对应的就是中位数了.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<stdio.h>

#define For(i,n) for(int i=0;i<n;++i)
int N1, N2, temp, res;

int main()
{
scanf("%d", &N1);
int S1[N1];
For(i,N1) scanf("%d", S1+i);
scanf("%d", &N2);
int midpos = (N1 + N2 - 1) / 2;
int i = 0, j = 0;
for( ; j<N2; ++j){
scanf("%d", &temp);
while (S1[i] < temp){
if ((i+j) == midpos) res = S1[i];
++ i;
if (i == N1) break;
}
if ((i+j) == midpos) res = temp;
}
while (i < N1){
if ((i+j) == midpos) res = S1[i];
++ i;
}
printf("%d\n", res);
return 0;
}

参考资源: https://www.liuchuo.net/archives/2248

PAT 真题 | 1057 Stack PAT 真题 | 1021 Deepest Root

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×