5-53 两个有序序列的中位数 (25分)
已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列
A0,A1,⋯,AN−1
的中位数指
A(N−1)/2
的值,即第
⌊(N+1)/2⌋
个数(
A0
为第1个数)。
输入格式:
输入分三行。第一行给出序列的公共长度N
(0<N≤100000)
,随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的并集序列的中位数。
输入样例1:
5
1 3 5 7 9
2 3 4 5 6
输出样例1:
4
输入样例2:
6
-100 -10 1 1 1 1
-50 0 2 3 4 5
输出样例2:
1
思路
生成两个链表(记录长度),比较寻找到中间的那一个,输出
#include <stdio.h>
#include<stdlib.h>
/* 评测结果 时间 结果 得分 题目 编译器 用时(ms) 内存(MB) 用户
2016-08-31 11:57 答案正确 25 5-53 gcc 44 1 569985011
测试点结果 测试点 结果 得分/满分 用时(ms) 内存(MB)
测试点1 答案正确 6/6 1 1
测试点2 答案正确 6/6 2 1
测试点3 答案正确 4/4 13 1
测试点4 答案正确 4/4 1 1
测试点5 答案正确 1/1 1 1
测试点6 答案正确 4/4 44 1
查看代码*/
int Move(int*,int*,int);
int main(){
int n;
scanf("%d",&n);
int*a=(int*)malloc(sizeof(int)*n);
int*b=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<n;i++)
scanf("%d",&b[i]);
int Result=Move(a,b,n);
printf("%d",Result);
return 0;
}
int Move(int*a,int*b,int n){
while(--n){
if(*a>=*b)++b;
else ++a;
// printf("%d-",(*a)>(*b)?(*b):(*a));
}
return (*a)>(*b)?(*b):(*a);
}