题目: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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
代码:
1)版本一:
1 public void merge1(int A[], int m, int B[], int n) { 2 int a = m - 1; 3 int b = n - 1; 4 int c = m + n -1; 5 while(a >= 0 && b >= 0){ 6 A[c--] = A[a] > B[b] ? A[a--]:B[b--]; 7 } 8 while(a >= 0) 9 A[c--] = A[a--]; 10 while(b >= 0) 11 A[c--] = B[b--]; 12 }
2)版本二:
1 public void merge2(int A[], int m, int B[], int n){ 2 for(int i = 0;i < n;i++){ 3 A[m+i]=B[i]; 4 } 5 Arrays.sort(A); 6 }
重点:二个版本的区别在于一自己写了过程使用从后往前插,避免大量移动元素。二将B拼接到A后,调用库排序。二者都能达到题目要求。