大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/merge-sorted-array/description/
内容
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.
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 + n
- nums2.length == n
- 0 <= m, n <= 200
- 1 <= m + n <= 200
- -109 <= nums1[i], nums2[j] <= 109
Follow up: Can you come up with an algorithm that runs in O(m + n) time?
解题
这题就是要将两个有序数组合并到其中一个数组中。相较于其他数组合并问题,这题要求数组合并到待合并的数组nums1地址空间中。nums1前m个元素是有序的,后n个数据位0,以保证整个空间可以正好存下两个数组的数据。为了防止元素的频繁移动,我们需要从后向前对比并布局数据。这样只要进行一次遍历,就可以将顺序排好。
#include <vector>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
auto nums1Index = m - 1;
auto nums2Index = n - 1;
auto nums1InsertIndex = m + n - 1;
while (nums2Index >= 0) {
if (nums1Index >= 0 && nums1[nums1Index] > nums2[nums2Index]) {
nums1[nums1InsertIndex--] = nums1[nums1Index--];
} else {
nums1[nums1InsertIndex--] = nums2[nums2Index--];
}
}
}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/88-Merge-Sorted-Array