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 elements initialized in A and B are m and n respectively.
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for (int i = 0; i < n; ++i) {
for (int j = m - 1; j >= -1; --j) { //注意 j >= -1
if (j >= 0 && A[j] > B[i]) {
A[j+1] = A[j];
} else {
A[j+1] = B[i];
++m;
break;
}
}
}
}
};
本文介绍了一种将两个已排序的整数数组B合并到数组A中并保持排序的方法。该算法通过移动元素的方式确保合并后的数组A仍然有序。文章提供了一个C++实现示例。
385

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



