题解 | #有序序列合并#
有序序列合并
https://www.nowcoder.com/practice/a9e943b0dab142759807d0cfb6863897
#include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int a[n], b[m], c[n+m];
int cnt = 0;
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
for (int i = 0; i < m; ++i)
{
cin >> b[i];
}
for (int i = 0, j = 0; ;)
{
while (i != n && j != m)
{
if (a[i] < b[j])
{
c[cnt] = a[i];
cnt++;
i++;
}
else
{
c[cnt] = b[j];
cnt++;
j++;
}
}
if (i == n)
{
if (j == m)
break;
c[cnt] = b[j];
cnt++;
j++;
}
if (j == m)
{
if (i == n)
break;
c[cnt] = a[i];
cnt++;
i++;
}
}
for (auto t: c)
{
cout << t << " ";
}
}
// 64 位输出请用 printf("%lld")
再定义一个数组,使用双指针的思路来解题。
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路
查看23道真题和解析