题目1004:Median 2011年浙江大学计算机及软件工程研究生机试真题

xiaoxiao2021-02-28  115

题目描述: S1={11, 12, 13, 14} is 12, S2={9, 10, 15, 16, 17} is 15. 输入: 输入:若干升序序列,每个序列两行,第一个数字表示数组元素个数。 输出: 每一个case中两个序列的中位数。

样例输入: 4 11 12 13 14 5 9 10 15 16 17 样例输出: 13

解题思路:把两个有序数组合并,sort,根据总长度直接找出中位数。

#include <stdio.h> #include <algorithm> using namespace std; int main() { int a,b; int s[200000]; while(scanf("%d",&a)!=EOF) { int i; int re; for(i=0;i<a;i++) { scanf("%d",&s[i]); } scanf("%d",&b); for(i=a;i<b+a;i++) { scanf("%d",&s[i]); } sort(s,s+a+b); re=(a+b)%2==0?((a+b)/2-1):(a+b-1)/2; printf("%d\n",s[re]); } return 0; }

这道题做的还不够完善,因为题目要求每个序列的元素个数N (≤1000000)。 如果固定初始化这么大的数组,会出错。只是九度OJ这个平台的测试用例少,没有边缘case,才会通过。先记录一下,有待完善

转载请注明原文地址: https://www.6miu.com/read-39316.html

最新回复(0)