题目
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.
合并两个排序好的数组。
由于数组空间足够,从后向前合并可减少操作。
代码:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int pos=m+n-1,pos_a=m-1,pos_b=n-1; //新数组的位置,a剩余的最大元素,b剩余的最大元素
while(pos>=0) //由后向前
{
if(pos_b<0)
return;
else if(pos_a<0||A[pos_a]<B[pos_b])
A[pos--]=B[pos_b--];
else
A[pos--]=A[pos_a--];
}
}
};