Merge Sorted Array 题解
题目来源:https://leetcode.com/problems/merge-sorted-array/description/
Description
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 nums1 and nums2 are m and n respectively.
Solution
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (i >= 0 && j >= 0) {
nums1[k--] = nums1[i] >= nums2[j] ? nums1[i--] : nums2[j--];
}
while (j >= 0) {
nums1[k--] = nums2[j--];
}
}
};
解题描述
这道题题意是,给出两个排好序的数组nums1
和nums2
,分别包含m
、n
个数字,nums1
总的空间不小于m + n
,要求合并两个数组,将结果存在nums1
中。也就是说,空余的空间一开始是在nums1
数组的尾部,算法就是从大到小进行归并,将结果依次插入到nums1
尾部即可,这样就不需要额外的空间保存归并的结果。