[ 问题: ]
Given two sorted integer arrays A and B, merge B into A as one sorted array.
直译:给定两个排好序的整形数组,将数组B合并到数组A,形成一个新的数组。
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.
[ 解法: ]
题解:从结尾开始归并,不会覆盖元素又能满足题意。
参数m:数组m位置后面元素会被数组B中元素替换
参数n:从第一个开始,将数组B中n个元素会被合并到数组A
public class Solution {
public static void main(String[] args) {
int[] A = { 1, 2, 4, 5, 6, 8 };
int[] B = { 3, 9, 10 };
new Solution().merge(A, 3, B, 2); // 1 2 3 4 9 8
}
public void merge(int A[], int m, int B[], int n) {
int i, j, k;
for (i = m - 1, j = n - 1, k = m + n - 1; k >= 0; --k) {
if (i >= 0 && (j < 0 || A[i] > B[j])) {
A[k] = A[i--];
} else {
A[k] = B[j--];
}
}
}
}
本文深入探讨了如何将两个已排序的整数数组合并为一个有序数组,详细介绍了算法实现过程,包括从数组尾部开始比较元素,并在合并过程中保持有序性。同时,解释了算法的时间复杂度和空间复杂度,提供了代码实现,适用于需要高效合并排序数组的场景。
324

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



