题目
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
思路
两个数组中位数的位置mid = (n1 + n2 - 1) / 2(从0计数)。
按照归并排序的思想,用两个指针分别指向两个有序数组的开始位置,移动较小一方的指针,直到移动次数达到mid为止。
需要注意的是,数据量大,程序开头添加:
ios::sync_with_stdio(false);
cin.tie(0);
以提高cin效率,否则最后一个测试点超时。
代码
#include <iostream>
#include <vector>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
vector<vector<int> > a(2);
for (int i=0; i<2; i++){
int n;
cin >> n;
a[i].resize(n);
for (int j=0; j<n; j++){
cin >> a[i][j];
}
}
int i = 0;
int j = 0;
int mid = (a[0].size() + a[1].size() - 1) / 2;
int count = -1;
while (i<a[0].size() && j<a[1].size()){
count++;
if (a[0][i] < a[1][j]){
if (count==mid){
cout << a[0][i];
break;
}
i++;
}
else{
if (count==mid){
cout << a[1][j];
break;
}
j++;
}
}
if (count < mid){
count++;
if (i==a[0].size()){
while(count<mid){
count++;
j++;
}
cout << a[1][j];
}
else if(j==a[1].size()){
while(count<mid){
count++;
i++;
}
cout << a[0][i];
}
}
cout << endl;
return 0;
}