88. Merge Sorted Array
题目描述
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
中文释义
你给定了两个整数数组 nums1 和 nums2,它们按非递减顺序排序,以及两个整数 m 和 n,分别代表 nums1 和 nums2 中的元素数量。
将 nums1 和 nums2 合并成一个按非递减顺序排序的单一数组。
最终排序的数组不应该由函数返回,而是应该存储在 nums1 数组内。为了适应这一点,nums1 的长度为 m + n,其中前 m 个元素表示应该合并的元素,而最后 n 个元素设置为0,应该被忽略。nums2 的长度为 n。
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9
解题思路
代码分析
-
变量初始化:
index从nums1的末尾开始(考虑到合并后的总长度),指向num1最后一个位置。index1从nums1的最后一个有效元素位置开始。index2从nums2的最后一个有效元素位置开始。
-
合并过程:
- 使用
while循环,直到index达到数组nums1的开始位置。 - 在每一步中,比较
nums1[index1]和nums2[index2]的值(如果index1和index2均大于等于0)。 - 将较大的值放入
nums1[index]的位置,并递减相应的索引(index1或index2)和index。 - 如果
nums1或nums2中的元素已经全部比较完毕(即index1或index2小于0),则将另一个数组中剩余的元素复制到nums1中。
- 使用
算法思路总结
- 这个问题的关键在于从后向前合并两个数组,这样可以避免在合并时覆盖
nums1中未处理的元素。 - 由于
nums1的大小足以容纳两个数组合并后的所有元素,因此可以在不需要额外空间的情况下完成合并。 - 通过从两个数组的末尾开始比较,可以确保在合并时不会丢失任何元素,并且每个元素只需要移动一次。
- 当其中一个数组的元素全部被合并后,如果另一个数组还有剩余元素,这些元素可以直接复制到
nums1的相应位置。
class Solution {
public:
// 合并两个有序数组nums1, nums2
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
// index 指向nums1数组末尾
// index1 指向nums1最后一个元素
// index2 指向nums2最后一个元素
int index = m + n - 1, index1 = m - 1, index2 = n - 1;
while (index >= 0) {
if (index1 >=0 && index2 >= 0) {
nums1[index--] = nums1[index1] > nums2[index2] ? nums1[index1--] : nums2[index2--];
} else if (index1 >= 0) {
nums1[index--] = nums1[index1--];
} else {
nums1[index--] = nums2[index2--];
}
}
}
};









