核心思路:游标记录已经遍历到当前位置
时间复杂度:m+n(两个数组的长度)
public class MergeDemo { /** * @param args */ public static void main(String[] args) { int[] a = {1,4,6,8}; int[] b = {3,5,7,10,20}; merger(a,b); int[] c = {1,2,3,4,5}; int[] d = {11,12,13,14,15}; merger(d,c); int[] e = {1,12,13,14,15}; int[] f = {11,12,13,14,15}; merger(e,f); } public static void merger(int[] a,int[] b){ int[] c = new int[a.length+b.length]; int indexA = 0; int indexB = 0; for(int i=0;i<c.length;i++){ if(indexA<a.length && indexB<b.length){ if(a[indexA]<=b[indexB]){ c[i] = a[indexA]; indexA++; }else{ c[i] = b[indexB]; indexB++; } }else if(indexA>=a.length&&indexB<b.length){ c[i] = b[indexB]; indexB++; }else if(indexB>=b.length&&indexA<a.length){ c[i] = a[indexA]; indexA++; } } for(int i=0;i<c.length;i++){ System.out.print(c[i]+" " ); } System.out.println(); } }