两个有序序列的中位数
题目描述
已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0,A1,⋯,AN−1的中位数指A(N−1)/2的值,即第[(N+1)/2]个数(A0为第1个数)。
只需考虑中位数唯一的情况
输入
输入分三行。第一行给出序列的公共长度N(0<N≤100000),随后每行输入一个序列的信息,即N个非降序排列的整数。数字用空格间隔。
输出
在一行中输出两个输入序列的并集序列的中位数。
输入样例:
5
1 3 5 7 9
2 3 4 5 6
输出样例:
4
参考代码:
#include <iostream>
#include <stack>
#include <vector>
#include <queue>
#include <list>
using namespace std;
int main() {
int len;
cin >> len;
queue<int> arr1;
queue<int> arr2;
for (int i = 0; i < len; ++i){
int num;
cin >> num;
arr1.push(num);
}
for (int i = 0; i < len; ++i){
int num;
cin >> num;
arr2.push(num);
}
for (int i = 0; i < (2 * len - 1) / 2; ++i)
if (arr1.front() < arr2.front())
arr1.pop();
else
arr2.pop();
if (arr1.front() < arr2.front())
cout << arr1.front() << endl;
else
cout << arr2.front() << endl;
return 0;
}