这是一个真实的面试题:题目要求合并2个有序的数组到一个数组中。
例如:int[] = new int[]{1,3,5}; int[] b = new int[]{2,4,6}; 合并完的结果是:[1,2,3,4,,5,6]
我的java代码实现如下:
public class MergeSortedArray { public static void main(String[] args) { int[] a = new int[]{11, 23, 33}; int[] b = new int[]{2, 4, 6}; int[] merged = mergeTowSortedArray(a, b); for (int i : merged){ System.out.println(i); } } /** * * @param a * @param b * @return */ public static int [] mergeTowSortedArray(int[] a, int[] b){ int[] c = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length || j < b.length){ //a数据已经遍历完了, if (i >= a.length){ c[k++] = b[j]; j++; continue; } if (j >= b.length){ c[k++] = a[i]; i++; continue; } if (a[i] <= b[j]){ c[k++] = a[i]; i++; continue; } c[k++] = b[j]; j++; } return c; }}