前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >合并数组 【归并 或 思维】

合并数组 【归并 或 思维】

作者头像
Lokinli
发布2023-03-09 13:54:40
4150
发布2023-03-09 13:54:40
举报
文章被收录于专栏:以终为始

合并数组

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 

代码语言:javascript
复制
5 5
1 2 2 3 3
5 4 3 2 1

Sample Output 1

代码语言:javascript
复制
1 1 2 2 2 3 3 3 4 5

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

代码语言:javascript
复制
#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;

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 合并数组
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档