Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.
需要判断边界情况。如果A和B为null的时候。不判定,则编译会出现空指针的报错。
因为B要合并到A里。那先比较前面的数据的话,会需要不断地往后移动数据。所以选择从后往前比较并插入。算法的时间复杂度是O(m+n),m和n分别是两个数组的长度,空间复杂度是O(1)。
public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { if(A==null||B==null) return; int indexA = m - 1; int indexB = n - 1; int i = m + n - 1; while (indexA >= 0 && indexB >= 0) { if (A[indexA] >= B[indexB]) { A[i] = A[indexA]; indexA--; i--; } else { A[i] = B[indexB]; indexB--; i--; } } //B结束了,A还有剩余的,不用管,反正数据都在A里。 //A结束了,B还有剩余的,则将B剩余数据直接复制到A里 while(indexB>=0){ A[i--]=B[indexB--]; }
} public void printArray(int[] C){ for(int i=0;i<C.length;i++){ System.out.print(C[i]+" "); } System.out.println("\n"); } public static void main(String[] args) { MergeSortedArray my = new MergeSortedArray(); int[] A=new int[20]; /* int m=6; for(int i=0;i<m;i++) A[i]=i+10; A=null;*/ int m=0; my.printArray(A); int[] B={6}; int n=1; my.printArray(B); my.merge(A, 0, B, n); my.printArray(A); } }=============
C#
public class Solution { public void Merge(int[] A, int m, int[] B, int n) { if (B.Length == 0 || B == null) return; int l = m + n - 1; m = m - 1; n = n - 1; while (m >= 0 && n >= 0) { if (B[n] <= A[m]) { A[l] = A[m]; m--; l--; } else { A[l] = B[n]; n--; l--; } } if (m < 0) while (n >= 0) { A[n] = B[n]; n--; } } }