Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
Given two increasing sequences of integers, you are asked to find their median.
Input
Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (<=1000000) is the size of that sequence. Then N integers follow, separated by a space. It is guaranteed that all the integers are in the range of long int.
Output
For each test case you should output the median of the two given sequences in a line.
Sample Input
4 11 12 13 14
5 9 10 15 16 17
Sample Output
13
题目大意
给出两个递增序列,求这两个序列合并后的中间数
思路
首先存储第一个序列,将其存在变量a中,然后在线读取并处理第二个序列。这两个序列合并后的中位数是从小到大的第(n+m+1)/2个。(这里要注意这个加1是为了四舍五入,比如9个元素的时候,中位数是第5个)。
首先初始化一个计数器count,初值为0。
一个指针i,初值为0,即指向第一个序列的第一个元素a[0]:
- 对于读入的第二个序列的每个元素t,我们作如下处理:
如果t>a[i],则将i向右移动直至t<=a[i]或者i移动到a尾部。(移动过程中更新自增计数器count的值,如果count==mid,即找到中位数,则终止函数,并返回该中位数)。 - 如果执行完上述步骤函数依然没有终止,即没有找到中位数,则说明中位数为a中
i向右(mid - count - 1)个。
更具体的细节看代码注释。
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int solve(){
// 读取第一个序列
int n;
scanf("%d", &n);
int a[n];
for(int i = 0; i < n;i++){
scanf("%d", &a[i]);
}
// 在线读取并处理第二个序列
int m;
scanf("%d", &m);
// 计算中位数是两个序列从小起第几个,初始化计数器和指针
int mid = (n + m + 1) / 2, count = 0, i = 0, temp;
while (m-- > 0) {
scanf("%d", &temp);
// 如果读进来的数字比a[i]大
// 则将i右移动,直到i移动到a数组最后一个元素或者temp比a[i]大,并更新计数器
while(i < n && temp > a[i]){
count++;
// 找到中位数a[i],返回结果
if(count == mid){
return a[i];
}
// 更新指针
i++;
}
count++;
// 找到中位数temp,返回结果
if(count == mid){
return temp;
}
}
// 如果到这都没返回,则中位数在a数组中上一个访问的元素的向右数(mid - count)个,这里-1是因为当前i总是访问的上一个元素的下标+1。
return a[i + mid - count - 1];
}
int main() {
printf("%d",solve());
return 0;
}