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
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.
思路:从后往前操作,可以避免很多操作。
class Solution{
public:
void merge(int A[],int m,int B[],int n)
{
int ia = m-1,ib = n-1,icur = m+n-1;
while(ia >= 0 && ib >= 0)
{
if(A[ia] > B[ib])
A[icur--] = A[ia--];
else
A[icur--] = B[ib--];
}
while(ib >= 0)
A[icur--] = B[ib--];
}
};
本文介绍了一种高效的方法来合并两个已排序的整数数组A和B,使得合并后的数组仍保持有序状态。此方法通过从数组末尾开始比较并放置较大元素的方式实现,有效地避免了中间过程中的大量移动操作。
322

被折叠的 条评论
为什么被折叠?



