Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.
分析:
1.A和B都已经是排好序的数组,我们只需要从后往前比较就可以了。因为A有足够的空间容纳A + B,我们使用游标i指向m + n - 1,也就是最大数值存放的地方,从后往前遍历A,B,谁大就放到i这里,同时递减i。
2.按照归并排序的惯性思路,因为归并排序中给定的是一个数组的两个区间,所以通常情况下会借助O(n)大小的辅助空间。
<pre name="code" class="cpp">#include "utility.h"
class Solution88
{
public:
void merge(int A[], int m, int B[], int n){
//采用尾插法,不需要辅助空间
int icur = m + n - 1;
int ia = m - 1;
int ib = n - 1;
while (ia >= 0 && ib >= 0){
if (A[ia] >= B[ib]){
A[icur] = A[ia];
icur--;
ia--;
}
else{
A[icur--] = B[ib--];
}
}
while (ib >= 0){
A[icur--] = B[ib--];
}
}
void merge1(int A[], int m, int B[], int n){
int temp[100];
int ia = 0, ib = 0, icur = 0;
while (ia < m&&ib < n){
if (A[ia] < B[ib])
temp[icur++] = A[ia++];
else
temp[icur++] = B[ib++];
}
while (ia < m){
temp[icur++] = A[ia++];
}
while (ib < n){
temp[icur++] = B[ib++];
}
while (--icur>0){
A[icur] = temp[icur];
}
}
};
int main()
{
Solution88 solution;
int a1[100] = { 1, 6, 9 };
int b1[] = { 2, 4, 7 };
solution.merge1(a1, 3, b1, 3);
for (int i = 0; i < 6; i++)
cout << a1[i] << endl;
getchar();
return 0;
}
本文深入探讨了如何高效地将两个已排序的整数数组合并为一个有序数组,通过对比两种不同的方法来优化合并过程,包括尾插法和辅助数组法,并详细解释了其背后的原理和适用场景。
322

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



