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×105) 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 |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 200 ms
内存限制: 1.5 MB
代码长度限制: 16 KB
题目大意
给出两个递增的数组,返回两个数组并集的中位数。
分析
类似Median of Two Sorted Arrays,一开始把Leetcode代码搬过来,发现内存超限。PAT这边更关注空间复杂度,Leetcode则更关注时间复杂度。这里参考柳婼 の blog的代码,但是一开始没有理解。后来想了一下,在此对其更进一步的解释:
- 下标从1开始,不论$(n+m)$奇偶,中位数mid为第$(n+m+1)/2$个数
- 只开一个数组存放数据,在线处理第二个数组,这样就不会超内存
- 使用i指向第一个数组,
count
计数,代表比temp
小的数的数量。读入第二个数组中的数记为temp
。 temp
与k[i]
比较,若temp
较大,则增大i
。此处循环,直到k[i]>temp
。每循环一次,都说明k[i]比temp
小,count++
。若count==mid
,说明到k[i]
为止(包括k[i]
),共有$mid$个数比temp
小。即temp
应放在$mid+1$的位置上,k[i]
即为$mid$位置上的数。- 上面循环结束后,$k[i]>temp$,
temp
应放在k[i-1]与k[i]之间的某个位置上,count++
,若==mid,则temp
即为$mid$位置上数。 - 若仍未找到,则中位数必在第一个数组中。(此时第二个数组中数据位置都已确定,出现这种情况必然是因为还没有找到第$mid$大的数。因为第二个数组已经读取完了,剩下的数必然在第一个数组中)。此时
k[i]
左边有$count$个数,当$count==mid-1$时,k[i]
在$mid$位置上,输出k[i]
代码
1 |
|