PAT A1029 Median (25 分)
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:
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 (≤2×10 ^ 5 ) 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 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的代码:
//two pointers方法解决;
#include<cstdio>
const int maxn = 1000100;
const int INF = 0x7fffffff;
int s1[maxn]={0},s2[maxn]={0};
int main(void){
int n1,n2;
scanf("%d",&n1);
for(int i=0;i<n1;i++){
scanf("%d",&s1[i]);
}
s1[n1] = INF;
scanf("%d",&n2);
for(int i=0;i<n2;i++){
scanf("%d",&s2[i]);
}
s2[n2] = INF;
int i=0,j=0,count=0;
int midian = (n1+n2-1)/2;
while(count<midian){//因为s1,s2的最后一个元素都是INF,不用考虑越界;
if(s1[i] < s2[j]){
i++;
}else j++;
count++;
}
if(s1[i]<s2[j]) printf("%d",s1[i]);
else printf("%d",s2[j]);
return 0;
}
思路:
这道题是算法笔记习题册上作为 two pointers 例题来讲解的,实际上用暴力法也不会超时;以下是使用暴力法的代码:
//暴力法解决;
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1000100;
long num[maxn]={0};
int main(void){
int n1,n2,n;
scanf("%d",&n1);
for(int i=1;i<=n1;i++){
scanf("%ld",&num[i]);
}
scanf("%d",&n2);
n=n1+n2;
for(int i=n1+1;i<=n;i++){
scanf("%ld",&num[i]);
}
int midian;
if(n%2) midian=n/2+1;
else midian=n/2;
sort(num+1,num+n+1);
printf("%ld",num[midian]);
return 0;
}