http://www.lintcode.com/en/problem/merge-two-sorted-arrays/#
归并排序的核心操作,要能够不假思索地写出来并bug-free。
class Solution {
public:
/**
* @param A and B: sorted integer array A and B.
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
int n1 = A.size(), n2 = B.size();
vector<int> ret(n1 + n2);
int p = 0, q = 0, k = 0;
while (p < n1 && q < n2) {
if (A[p] < B[q]) ret[k++] = A[p++];
else ret[k++] = B[q++];
}
while (p < n1) {
ret[k++] = A[p++];
}
while (q < n2) {
ret[k++] = B[q++];
}
return ret;
}
};
本文介绍了一个核心的归并排序操作:合并两个已排序的数组。通过一个简洁的C++代码示例,展示了如何将两个有序整数数组A和B合并成一个新的有序数组。此方法适用于各种需要数组合并的场景。

414

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



