求两个长度相同的升序数组的中位数
2016-06-20 15:54
225 查看
题解:
(1)若a=b ,则 a 或 b 即为所求的中位数,算法结束
(2)若a<b ,则舍弃序列A中较小的一半,同时舍弃序列B中较大的一半,要求两次舍弃的长度相等
(3)若a>b ,则舍弃序列A中较大的一半,同时舍弃序列B中较小的一半,要求两次舍弃的长度相等
在保留的两个升序序列中,重复过程(1)(2)(3),直到两个序列中均只含一个元素时为止,较小者即为中位数
代码:
#include<cstdlib>
#include<string>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<ctime>
#include<stack>
#include<map>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
int M_search(int* a,int* b,int n)
{
int s1=0,d1=n-1,m1,s2=0,d2=n-1,m2;
while(s1!=d1 || s2!=d2)
{
m1=(s1+d1)/2;
m2=(s2+d2)/2;
if(a[m1]==b[m1]) //满足条件1
return a[m1];
if(a[m1]<b[m2]) //满足条件2
{
if((s1+d1)%2==0) //若元素的个数为奇数
{
s1 = m1;
d2 = m2;
}
else
{
s1 = m1+1;
d2 = m2;
}
}
else //满足条件3
{
if((s1+d1)%2==0)
{
d1 = m1;
s2 = m2;
}
else
{
d1 = m1;
s2 = m2+1;
}
}
}
return a[s1]<b[s2] ? a[s1]:b[s2];
}
int main()
{
int a[10]={1,3,5,7,9};
int b[10]={2,4,6,8,10};
cout<<M_search(a,b,5)<<endl;
return 0;
}
(1)若a=b ,则 a 或 b 即为所求的中位数,算法结束
(2)若a<b ,则舍弃序列A中较小的一半,同时舍弃序列B中较大的一半,要求两次舍弃的长度相等
(3)若a>b ,则舍弃序列A中较大的一半,同时舍弃序列B中较小的一半,要求两次舍弃的长度相等
在保留的两个升序序列中,重复过程(1)(2)(3),直到两个序列中均只含一个元素时为止,较小者即为中位数
代码:
#include<cstdlib>
#include<string>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<ctime>
#include<stack>
#include<map>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
int M_search(int* a,int* b,int n)
{
int s1=0,d1=n-1,m1,s2=0,d2=n-1,m2;
while(s1!=d1 || s2!=d2)
{
m1=(s1+d1)/2;
m2=(s2+d2)/2;
if(a[m1]==b[m1]) //满足条件1
return a[m1];
if(a[m1]<b[m2]) //满足条件2
{
if((s1+d1)%2==0) //若元素的个数为奇数
{
s1 = m1;
d2 = m2;
}
else
{
s1 = m1+1;
d2 = m2;
}
}
else //满足条件3
{
if((s1+d1)%2==0)
{
d1 = m1;
s2 = m2;
}
else
{
d1 = m1;
s2 = m2+1;
}
}
}
return a[s1]<b[s2] ? a[s1]:b[s2];
}
int main()
{
int a[10]={1,3,5,7,9};
int b[10]={2,4,6,8,10};
cout<<M_search(a,b,5)<<endl;
return 0;
}
相关文章推荐
- 个人冲刺10
- java Exception in thread "main" java.lang.NoClassDefFoundError: (wrong name: ) 解决方案
- Android layer-list:联合shape(2)
- HTML下使元素在父元素内绝对定位
- Python中Iterator迭代器的使用杂谈
- java开发编译器:自底向上语法解析的基本原理
- 编程之美:扫雷的概率
- Android layer-list:联合shape(2)
- HDU 3523 最小费用流或KM
- Android水波纹特效的简单实现
- 吴柄锡 github----MHA helper
- 【转】iOS类似Android上toast效果
- 锁屏简介
- WINDOWS中NEXUS的安装使用【ATCO整理】
- Win10+SSD卡顿问题
- 好多东西要学习啊
- 数据嗨客 | 第6期:不平衡数据处理
- const 指针与指向const的指针
- 关于Masonry与Block
- 使用Intellij构建spark源码阅读环境