一、题目描述
原题链接
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 Specification:
Output Specification:
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
二、解题思路
这道题主要是将两个数组中的数进行排序,随后把在中间的数输出即可。这里用的是双指针法,不难理解,代码也非常简单,这里为了省时间,我并没有把两个数组完整排列出来,而是采用了到了位置就输出的方法。代码非常易理解,附在下方。
三、AC代码
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int maxn = 200010;
typedef long long LL;
LL a[maxn] = {0}, b[maxn] = {0};
int main()
{
int na, nb, cnt=0;
scanf("%d", &na);
for(int i=1; i<=na; i++)
scanf("%lld", &a[i]);
scanf("%d", &nb);
for(int i=1; i<=nb; i++)
scanf("%lld", &b[i]);
int ptr_a = 1, ptr_b = 1;
int mk;
if((na+nb)%2 == 0) mk = (na+nb)/2;
else mk = (na+nb)/2 + 1;
while(ptr_a<=na && ptr_b<=nb)
{
cnt++;
if(a[ptr_a] < b[ptr_b])
{
ptr_a++;
if(cnt == mk)
{
printf("%lld", a[ptr_a-1]);
return 0;
}
}
else
{
ptr_b++;
if(cnt == mk)
{
printf("%lld", b[ptr_b-1]);
return 0;
}
}
}
if(cnt < mk)
printf("%lld", ptr_a == na+1 ? b[ptr_b+mk-cnt-1] : a[ptr_a+mk-cnt-1]);
return 0;
}