1029. Median (25)
2014-01-28 13:30
483 查看
GivenanincreasingsequenceSofNintegers,themedianisthenumberatthemiddleposition.Forexample,themedianofS1={11,12,13,14}is12,andthemedianofS2={9,10,15,16,17}is15.Themedianoftwosequencesisdefinedtobethe
medianofthenondecreasingsequencewhichcontainsalltheelementsofbothsequences.Forexample,themedianofS1andS2is13.
Giventwoincreasingsequencesofintegers,youareaskedtofindtheirmedian.
Input
Eachinputfilecontainsonetestcase.Eachcaseoccupies2lines,eachgivestheinformationofasequence.Foreachsequence,thefirstpositiveintegerN(<=1000000)isthesizeofthatsequence.ThenNintegersfollow,separatedbyaspace.Itis
guaranteedthatalltheintegersareintherangeoflongint.
Output
Foreachtestcaseyoushouldoutputthemedianofthetwogivensequencesinaline.
SampleInput
SampleOutput
[/code]
medianofthenondecreasingsequencewhichcontainsalltheelementsofbothsequences.Forexample,themedianofS1andS2is13.
Giventwoincreasingsequencesofintegers,youareaskedtofindtheirmedian.
Input
Eachinputfilecontainsonetestcase.Eachcaseoccupies2lines,eachgivestheinformationofasequence.Foreachsequence,thefirstpositiveintegerN(<=1000000)isthesizeofthatsequence.ThenNintegersfollow,separatedbyaspace.Itis
guaranteedthatalltheintegersareintherangeoflongint.
Output
Foreachtestcaseyoushouldoutputthemedianofthetwogivensequencesinaline.
SampleInput
411121314 5910151617
SampleOutput
13
注意点:因为给出的数据很有特点(已经有序),用快速排序的话时间复杂度为O(NlogN)还是有两个测试点通不过,通过可并排序的方法的时间复杂度为O(N+M)可以AC,注意不要用C++的流来完成数据的输入,会有很多测试点超时,要用stdio.h库的scanf()和printf()来完成
参考代码:
#include<iostream>
#include<stdio.h>
usingnamespacestd;
intmain()
{
intM,N;
scanf("%d",&M);
int*arr1=newint[M];
for(inti=0;i<M;i++){
scanf("%d",arr1+i);
}
scanf("%d",&N);
int*arr2=newint
;
for(inti=0;i<N;i++){
scanf("%d",arr2+i);
}
intK=M+N;
int*arr3=newint[K];
intstart=0,p1=0,p2=0;
while(p1!=M||p2!=N){
if(p1==M){
arr3[start++]=arr2[p2++];
continue;
}
if(p2==N){
arr3[start++]=arr1[p1++];
continue;
}
if(arr1[p1]<arr2[p2]){
arr3[start++]=arr1[p1++];
}else{
arr3[start++]=arr2[p2++];
}
}
if(K%2==0)
printf("%d",arr3[K/2-1]);
else
printf("%d",arr3[K/2]);
return0;
}
[/code]
相关文章推荐
- 一个简单的音乐贺卡
- ORACLE空间管理实验7:块管理之MMSM--为什么SYSTEM/UNDO/TEMP是MMSM管理?
- c for循环嵌套switch的用法
- 黑马程序员--命名空间和索引器小结
- 硬盘IO,SAS,SATA,和HD TUNE
- 数组中只出现一次的数字
- jQuery实现复选框的全选和反选:
- 用Excel打开csv文件时,如何处理数字内容展现会自动转换格式的问题
- [LeetCode] - Interleaving String
- Double 浮点小数相加减乘除
- CentOS 6.3下部署LVS(NAT)+keepalived实现高性能高可用负载均衡
- 各种数据库连接
- 第四章 禅坐和外相的修行
- 2013年度工作学习总结报告
- VBX 如何使虚拟机支持多核
- 预编译的作用
- 踢猫效应的故事
- RPM方式安装MySQL5.6
- 运算符重载 hash原理 Equals方法
- unknow table alarmtemp error when drop database (mysql)