Median
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
题意
给定两组升序整数数组,要求输出将它们合并并升序排列后的中位数。
思路
典型的两数组有序归并问题,直接套用模版即可。
没想到的是,直接排序也可以通过,并且开销更小……
代码实现——归并
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> merge(vector<int> a, vector<int> b) // 数组归并
{
int i = 0, j = 0;
vector<int> c;
while (i < a.size() && j < b.size())
{
if (a[i] < b[j])
c.push_back(a[i++]);
else if (a[i] > b[j])
c.push_back(b[j++]);
else
{
c.push_back(a[i++]);
j++;
}
}
while (i < a.size())
c.push_back(a[i++]);
while (j < b.size())
c.push_back(b[j++]);
return c;
}
int main()
{
int n;
int x;
vector<int> a, b, ans;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
a.push_back(x);
}
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
b.push_back(x);
}
ans = merge(a, b);
printf("%d", ans[(ans.size() - 1) / 2]);
return 0;
}
代码实现——直接排序
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int x;
vector<int> a, b, ans;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
a.push_back(x);
}
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &x);
a.push_back(x);
}
sort(a.begin(), a.end()); // 排序
printf("%d", a[(a.size() - 1) / 2]);
return 0;
}