面试时遇到的题,答的不太好。回来写了写,很简单,为什么当时没有写好呢?
/* * Jason Li 2014-5 * 两个有序数组中的数组,合并到新的有序数组 */public class OrderedArrayCombination { public static void main(String[] args) { int[] arrayA = { 1, 3, 5, 7, 9 }; int[] arrayB = { 2, 4, 6, 8, 10 }; int[] arrayC = new int[arrayA.length + arrayB.length]; int indexA = 0, indexB = 0, indexC = 0; //合并 while (indexA < arrayA.length && indexB < arrayB.length) { if (arrayA[indexA] < arrayB[indexB]) { arrayC[indexC++] = arrayA[indexA++]; } else { arrayC[indexC++] = arrayB[indexB++]; } } //如果A数组有剩余元素,将A中所有数据加入C while (indexA < arrayA.length) { arrayC[indexC++] = arrayA[indexA++]; } //如果B数组有剩余元素,将B中所有数据加入C while (indexB < arrayB.length) { arrayC[indexC++] = arrayB[indexB++]; } // 输出 for (int i = 0; i < arrayC.length; i++) { System.out.print(arrayC[i] + " "); } System.out.println(); }}