这道题目通过率非常低, 自己也是花了大半天功夫才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 | 4 11 12 13 14 |
Sample Output:
1 | 13 |
时间限制: 200 ms
内存限制: 1.5 MB
代码长度限制: 16 KB
题目分析
这道题给出两个排好序的串, 求合并后有序串的中位数. 这道题的难点在于内存限制得很小, 无法满足开两个数组储存两个整数串, 只能开一个. 这道题主要的一个坑点是题目说整数全部在long int(8 bytes) 范围内, 实际全部是 int(4 bytes) 范围内. 解题思路是开一个int数组, 先把第一个串存进来. 然后动态读取第二个数组, 在读取的同时进行比较, 模拟归并排序. 最后若读取完毕第一个串还没有读取完毕, 则继续读取第一个串. 全过程位置不断增加, 中间位置 midpos 对应的就是中位数了.
1 | #include<stdio.h> |
评论
shortname
for Disqus. Please set it in_config.yml
.