1. 程式人生 > >ZZULIOJ 1124: 兩個有序數組合並

ZZULIOJ 1124: 兩個有序數組合並

題目描述

已知陣列a中有m個按升序序排列的元素,陣列b中有n個降序排列的元素,程式設計將a與b中的所有元素按降序存入陣列c中。

 

輸入

輸入有兩行,第一行首先是一個正整數m,然後是m個整數;第二行首先是一個正整數n,然後是n個整數,m, n均小於等於1000000。

 

輸出

輸出合併後的m+n個整數,資料之間用空格隔開。輸出佔一行。

 

樣例輸入

<span style="color:#333333">4 1 2 5 7
3 6 4 2
</span>

 

樣例輸出

<span style="color:#333333">7 6 5 4 2 2 1
</span>

 

提示

試圖排序的孩子們要小心了~~~~~~

import java.util.Arrays;
import java.util.Scanner;

public class Main {

        public static  int[] merge (int[] a, int[] b) {
                int pa =0;
                int pb = 0;
                int pc = 0;
                int m = a.length;
                int n = b.length;
                int[] c = new int[m+n];
                while (pa<m && pb<n) {
                        if (a[pa]<b[pb]) {
                                c[pc++] = a[pa++];
                        }else {
                                c[pc++] =b[pb++];
                        }
                }
                if (pa<m)
                        while (pa<m) c[pc++] = a[pa++];
                else
                        while (pb<n) c[pc++] = b[pb++];
                return c;
        }


        public static void main(String[] args) {

                Scanner input=new Scanner(System.in);
                int n=input.nextInt();
                int[] arr=new int[n];
                for (int i=0;i<n;i++){
                        int num=input.nextInt();
                        arr[i]=num;
                }

                int m=input.nextInt();
                int[] brr=new int[m];

                for (int i=0;i<m;i++){
                        int num=input.nextInt();
                        brr[i]=num;
                }

               int[] crr=Main.merge(arr,brr);

                //對陣列升序
                Arrays.sort(crr);


                //倒序列印陣列元素
                for (int i=crr.length-1;i>=0;i--){
                        System.out.print(crr[i]+" ");
                }


        }
}