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.
思路:从A的m+n-1开始存放,比较A和B的尾数的大小,大的就往lastMax位置上放,对应的lastMax和相应的A、B尾下标往前移动。
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(n <= 0)
return;
int lastMax = n + m -1;
while(m > 0 && n >0){
if(A[m-1] >= B[n-1]){
A[lastMax--] = A[m-1];
m--;
}
else {
A[lastMax--] = B[n-1];
n--;
}
}
if(m==0){
while(n>0){
A[lastMax--] = B[n-1];
n--;
}
}
}
};