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为空的情况。此外从后往前插入元素即可。
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int index=m+n-1,i=m-1,j=n-1;
if(m==0)
{
for(int k=n-1;k>=0;k--)
A[k]=B[k];
return ;
}
else if(n==0)
{
return ;
}
while(i>=0&&j>=0)
if(A[i]>B[j])
A[index--]=A[i--];
else
A[index--]=B[j--];
while(j>=0)
A[index--]=B[j--];
}
};