给定2个非降序序列,要求把他们合并成1个非降序序列。假设所有元素个数为N,要求算法的时间复杂度为O(N)。
输入格式:
输入有4行。
第1行是一个正整数m,表示第2行有m个整数,这些整数构成一个非降序序列,每个整数之间以空格隔开。第3行是一个正整数n,表示第4行有n个整数,这些整数也构成一个非降序序列,每个整数之间以空格隔开。
输出格式:
把第2行的m个整数和第4行的n个整数合并成一个非降序序列,输出这个整数序列。每个数之间隔1个空格。
输入样例:
6
1 3 6 6 8 9
4
2 4 5 7
输出样例:
1 2 3 4 5 6 6 7 8 9
#include<bits/stdc++.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n;
vector<int>v1;
for (int i = 0; i < n; i++)
{
cin >> m;
v1.push_back(m);
}
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> m;
v1.push_back(m);
}
sort(v1.begin(), v1.end());
for (auto i : v1)
{
cout << i << " ";
}
}
//以下提供结构体的写法
struct List
{
int* Data;
int len;
List(int num)
{
this->Data = new int[num + 1];
this->len = num;
for (int i = 0; i < num; i++)
{
cin >> this->Data[i];
}
}
void mincout(List* L)
{
if (L->len == 0)
{
for (int i = 0; i < this->len; i++)
{
cout << this->Data[i] << " ";
}
}
else if (this->len == 0)
{
for (int i = 0; i < L->len; i++)
{
cout << L->Data[i] << " ";
}
}
else
{
int s1 = 0, s2 = 0;
while (s1 != this->len || s2 != L->len)
{
if (s1 == this->len)
{
cout << L->Data[s2++] << " ";
}
else if (s2 == L->len)
{
cout << this->Data[s1++] << " ";
}
else if (this->Data[s1] > L->Data[s2])
{
cout << L->Data[s2++] << " ";
}
else
{
cout << this->Data[s1++] << " ";
}
}
}
}
};
int main()
{
int n;
cin >> n;
List* L1 = new List(n);
cin >> n;
List* L2 = new List(n);
L1->mincout(L2);
}