文章目录

1 题目

1029 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

2 解析

2.1 题意

找到组合后非递减的序列中的中位数

2.2 思路

  • 1 用双指针法,指针i和指针j分别指向输入的数组A和数组B;
  • 2 准备:用count统计当前的个数。组合后的中位数位置为:如果组合后的序列长度为偶数,则mid = (A.len + B.len)/2;如果为奇数,则mid = (A.len + B.len+1)/2;
  • 3 如果i指向数组A的值小于或等于j指向的数组的值,则count++、i++;否则,则cout++,j++;在count++之后,判断count是否等于mid如果等于,则终止循环(循环条件为i<A.len&&j<B.len);
  • 4 如果比较完数组A(iA.len时,count仍未等于mid)或者比较完数组B(jB.len时,count仍未等于mid)后,仍未找到中位数,则继续比较剩余一个数组,直到找中位数的位置。

3 参考代码

#include 

const int INF = 0x7fffffff;
const int MAXN = 1000010;
int A[MAXN], B[MAXN];

int main(int argc, char const *argv[]){
int n, m;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &A[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; ++i) {
scanf("%d", &B[i]);
}

int mid;//组合后的中位数的位置
if((n + m) % 2 == 0){
mid = (n + m) /2;
}else{
mid = (n + m + 1)/2;
}
int i = 0, j = 0;//i指向数组A的下标,j指向数组B的下标
int count = 0, ans = -1;//个数,组合后的中位数
while(i < n && j < m){
if(A[i] <= B[j]){//如果i指向的数组A的值小于等于j指向数组B的值
count++;
if(count == mid){//个数等于中位数
ans = A[i];
break;
}
i++;
}else{
count++;
if(count == mid){
ans = B[j];
break;
}
j++;
}
}

while(i < n && j == m){//比较完数组B后,继续比较数组A
count++;
if(count == mid){
ans = A[i];
break;
}
i++;
}

while(j < m && i == n){//比较完数组A后,继续比较数组B
count++;
if(count == mid){
ans = B[j];
break;
}
j++;
}
printf("%d", ans);
return 0;
}