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 Input4 11 12 13 14 5 9 10 15 16 17Sample Output
13
備註: 兩個數組各設一個指針,比較當前數大小,小的那個指針向前走一步,同時判斷是否爲中位數,注意不能數組越界。
#include<stdio.h>
int main()
{
int n1,n2,middle;
long int *a,*b;
scanf("%d",&n1);
a = new long[n1];
for(int i=0;i<n1;i++)
scanf("%ld",&a[i]);
scanf("%d",&n2);
b = new long[n2];
for(int i=0;i<n2;i++)
scanf("%ld",&b[i]);
if((n1+n2)%2==0)
middle = (n1+n2)/2;
else
middle = (n1+n2+1)/2;
int i=0,j=0,median=-1;
int count=0;
while(i<n1 && j<n2) // i and j must not exceed the length range
{
if(a[i]>b[j])
{
median = b[j];
j++;
count++;
}
else if(a[i]<=b[j])
{
median = a[i];
i++;
count++;
}
if(count==middle)
{
printf("%ld",median);
return 0;
}
}
if(i==n1)
printf("%ld",b[middle-n1+j-1]);
else if(j==n2)
printf("%ld",a[middle-n2+i-1]);
return 0;
}