题目描述:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中的所有数字插入A1中,并且所有数字是排序的。
分析:因为两个数组都已经排序了,切A1的末尾有足够的空间,那我们就从末尾这个角度来解。从A1和A2的末尾开始比较,将更大的放在A1容量的末尾,然后向前扫描。因为是用c#写,所以我是重新声明了一个数组来存储A1和A2的值。
代码如下:
private static int[] CombineSortArray(int[] A1,int[] A2) { if (A1 == null || A2 == null) return new int[] { 0 }; int a1Len = A1.Length; int a2Len = A2.Length; int newLen = a1Len + a2Len; int[] result = new int[newLen]; for(int i=a1Len-1,j=a2Len-1;i>=0 || j>=0;) { //判断A1、A2是否取完 if(i<0) { result[newLen - 1] = A2[j]; j--; newLen--; continue; } if (j < 0) { result[newLen - 1] = A1[i]; i--; newLen--; continue; } if (A1[i]>A2[j]) { result[newLen - 1] = A1[i]; i--; } else { result[newLen - 1] = A2[j]; j--; } newLen--; } return result; }总结:写得不够优雅,判断太多了。