兩個有序序列的中位數
已知有兩個等長的非降序序列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 <iostream>
using namespace std;
#define MN 110000
int a[MN], b[MN], n;
int main(){
cin>>n;
for(int i = 0; i < n; ++i)
cin>>a[i];
for(int i = 0; i < n; ++i)
cin>>b[i];
int ai, bi;
ai = bi = 0;
while(ai + bi != n - 1) {
if(a[ai] > b[bi])
bi++;
else
ai++;
}
a[ai] > b[bi] ? cout<<b[bi] :cout<< a[ai];
}