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 m and n respectively.
思路:从为了不覆盖未比较的元素,后往前比较数组A和B中元素的大小,并从后更新元素。
1 class Solution { 2 public: 3 void merge(int A[], int m, int B[], int n) { 4 int i=m-1,j=n-1,k=m+n-1; 5 while(i>=0&&j>=0) 6 { 7 if(A[i]>B[j]) 8 A[k--]=A[i--]; 9 else 10 A[k--]=B[j--]; 11 } 12 while(j>=0) 13 A[k--]=B[j--]; 14 } 15 };