7-4 The median of two ordered sequences (25 points)
Given that there are two equal-length non-descending sequences S1, S2, design the function to find the median of the union of S1 and S2. The median of the ordered sequence A0,A1,...,AN−1refers to the value of A(N−1)/2, that is, the first ⌊(N+1 )/2⌋ number (A0is the first number).
Input format:
The input is divided into three lines. The first line gives the common length of the sequence N (0<N≤100000), and then each line enters the information of a sequence, that is, N integers in non-descending order. The numbers are separated by spaces.
Output format:
Output the median of the union sequence of the two input sequences in one line.
Input example 1:
5
1 3 5 7 9
2 3 4 5 6
Output sample 1:
4
Input example 2:
6
-100 -10 1 1 1 1
-50 0 2 3 4 5
Output sample 2:
1
Rearrange the two ordered sequences, (do not remove the duplicates, find the median);
Method 1: Input first, then compare and sort one by one
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
vector<int>a,b,c;
int x;
for(int i=0;i<n;++i)
{
cin>>x;
a.push_back(x);
}
for(int i=0;i<n;++i)
{
cin>>x;
b.push_back(x);
}
int i=0,j=0;
//把二者中小的一方放入数组c
while(!a.empty()&&!b.empty())
{
if(a[i]>b[j])
{
c.push_back(b[j++]);
b.pop_back();
}
else
{
c.push_back(a[i++]);
a.pop_back();
}
}
if(!a.empty())
{
while(!a.empty())
{
c.push_back(a[i++]);
a.pop_back();
}
}
if(!b.empty())
{
while(!b.empty())
{
c.push_back(b[j++]);
b.pop_back();
}
}
int len=(c.size()-2)/2;
cout<<c[len];
return 0;
}
Method one can also put a counter when comparing the size, who is the n-1th number (the initial value of the counter is set to -1), who is the median
Method 2: Sort directly with sort
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
vector<int>a;
int x;
for(int i=0;i<2*n;++i)
{
cin>>x;
a.push_back(x); //vector不能直接使用cin>>a[i]; vecor只是声明,没有开辟内存
}
sort(a.begin(),a.end());//对vecotr使用sort排序
cout<<a[n-1];//(2*n-2)/2=n-1
return 0;
}