题目描述
编写一个程序,将两个有序数组合并成一个更大的有序数组,要求时间复杂度为O(n)。
输入
多组数据输入,每组输入包括两行,每行第一个数字为数组长度n,然后输入n个有序整数。
输出
输出合并后的数组(升序),每组输出用两个空行隔开。
样例输入 Copy
3 1 3 5 3 2 4 6 2 1 2 4 3 4 5 6
样例输出 Copy
1 2 3 4 5 6 1 2 3 4 5 6
用双指针,从后往前比较;
时间复杂度为O(n);
import java.util.Scanner;
public class Main{
public static void f(int[] num1,int m,int[] num2,int n){
int p1=m-1;
int p2=n-1;
int p=m+n-1;
int c[]=new int[num1.length+num2.length];
while((p1>=0)&&(p2>=0))
c[p--]=(num1[p1]<num2[p2])?num2[p2--]:num1[p1--];
while((p1>=0)&&(p2==-1))
c[p--]=num1[p1--];
while((p2>=0)&&(p1==-1))
c[p--]=num2[p2--];
for(int i=0;i<c.length;i++){
System.out.printf("%d ",c[i]);
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
while(scan.hasNext()){
int n=scan.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=scan.nextInt();
}
int m=scan.nextInt();
int b[]=new int[m];
for(int i=0;i<m;i++){
b[i]=scan.nextInt();
}
f(a,n,b,m);
}
}
}