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
算法分析:
采用两个数组存储两组数列,对应的长度为lenA和lenB。在合并两个数组时,本来需要一个长度为lenA+lenB的数组来存储合并的结果,但是现在可以用一个变量tmp来存储最后放入数组的值,k是其对应的下标,因为之前的值不需要用,所以可以这么做。
然后就是将两个数组的第一个值作比较,其中较小的一个就存入tmp,较大的一个留下继续比较,tmp每存进一个数,下标k要++。用变量opj来表示合并两个数组之后中间位置的下标,要输出的结构就是opj下标对应的值。对于推出while循环的条件有三种,第一种是数组a的元素都存进了tmp,第二种是数组b的元素都放进了tmp,第三种最好,k到了opj的位置,直接就得到最终结果。
但是一个数组存放完,k又没到opj的位置,就存在两种情况。第一种是数组a没放完,数组b放完,那就把数组a一个一个放进tmp,直到k满足条件。第二种情况类似,不再赘述。具体见代码注释。
#include <stdio.h>
#include <stdlib.h>
long long a[1000000] = {0}, b[1000000] = {0};
int main()
{
int i, j, lenA, lenB, k;
scanf("%d", &lenA);
for(i = 0; i < lenA; i++)
scanf("%lld", &a[i]);
scanf("%d", &lenB);
for(i = 0; i < lenB; i++)
scanf("%lld", &b[i]);
long long tmp;
int opj = (lenA + lenB - 1) / 2;
i = 0, j = 0, k = -1;
while(i < lenA && j < lenB && k < opj)
{
if(a[i] < b[j]) //当a[i]<b[j]时,就把a[i]放进tmp,b[j]不动与接下来的a[i++]继续比较。
tmp = a[i++];
else if(a[i] > b[j])
tmp = b[j++];
else //这里需要注意,当两个数相等的时候,需要一次存放两个数,所以k的值要加2。
{
tmp = a[i++];
k++;
j++;
}
k++;
}
while(i < lenA && k < opj) //数组a没放完,数组b放完。
{
tmp = a[i++];
k++;
}
while(j < lenB && k < opj)
{
tmp = b[j++];
k++;
}
printf("%lld", tmp);
return 0;
}