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 end = m + n -1;
while(m > 0 && n >0)
{
if (A[m-1] >= B[n-1])
A[end--] = A[--m];
else
A[end--] = B[--n];
}
if (n > 0)
memcpy(A, B, sizeof(int) * n);
}
};
本文介绍了一个C++方法,用于将两个已排序的整数数组B合并到A中,使其成为一个有序数组。假设A有足够的空间来容纳B中的额外元素。通过比较两个数组的末尾元素并逆向填充结果,该方法有效地完成了任务。
325

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



