给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nums2 的元素。
示例 1:
输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
输出:[1,2,2,3,5,6]
示例 2:
输入:nums1 = [1], m = 1, nums2 = [], n = 0
输出:[1]
提示:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[i] <= 109
老题,从后往前。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if (n == 0) {
return;
}
if (m == 0) {
nums1 = nums2;
return;
}
int index1 = m - 1;
int index2 = n - 1;
int index = m + n - 1;
vector<int> nums(nums1.size(), 0);
while (index1 >= 0 && index2 >= 0) {
if (nums1[index1] > nums2[index2]) {
nums1[index--] = nums1[index1--];
}
else {
nums1[index--] = nums2[index2--];
}
}
while (index1 >= 0) {
nums1[index--] = nums1[index1--];
}
while (index2 >= 0) {
nums1[index--] = nums2[index2--];
}
}
};
int main() {
vector<int> nums1 = { 1, 2, 3, 0, 0, 0 };
vector<int> nums2 = { 2, 5, 6 };
Solution* ps = new Solution();
ps->merge(nums1, 3, nums2, 3);
for (int i = 0; i < nums1.size(); i++) {
cout << nums1[i] << endl;
}
system("pause");
return 0;
}