0
点赞
收藏
分享

微信扫一扫

合并数组 【归并 或 思维】


合并数组

Description

给定两个有序数组,第一个增序,第二个降序,输出两个数组合并后的增序数组。

Input

第一行两个整数n和m。(1<=n<=100000,1<=m<=100000)

第二行n个整数ai。(1<=a[i]<=1e9,a[i]<=a[i+1])

第三行m个整数bi。(1<=b[i]<=1e9,b[i]>=b[i+1])

Output

输出一行,表示合并后的增序数组。

Sample Input 1 


5 5 1 2 2 3 3 5 4 3 2 1


Sample Output 1


1 1 2 2 2 3 3 3 4 5


解析:这里非正规做法-归并排序。

#include <stdio.h>
#include <string.h>
//#include<bits/stdc++.h>
//using namespace std;

int a[100005];
int b[100005];
int c[300005];
int main()
{
int n,m;
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i ++)scanf("%d",&a[i]);
for(int i = 0; i < m; i ++) scanf("%d", &b[i]);
int topA = 0;
int topB = m - 1;
int top = 0;
while(1){
if(a[topA] > b[topB]){
c[top++]=b[topB];
topB --;
}
else {
c[top++]=a[topA];
topA++;
}
if(topA == n || topB == -1) break;
}
while(topA<n){
c[top++]=a[topA++];
}
while(topB >= 0){
c[top++]=b[topB--];
}
for(int i = 0; i < n + m; i ++){
if(i == 0)printf("%d",c[i]);
else printf(" %d",c[i]);
}
printf("\n");
return 0;

}

 

举报

相关推荐

0 条评论