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.
Link:
https://leetcode.com/problems/merge-sorted-array/#/description
解题方法:
先把nums1的元素整体往后挪n位,然后在以nums1为容器排序。
Time Complexity:
空间:O(1)
时间:O(N)
完整代码:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
for(int i = m - 1, j = m + n - 1; i >= 0; i--, j--)
nums1[j] = nums1[i];
int start1 = n;
int start2 = 0;
int move = 0;
while(start1 < m + n || start2 < n)
{
if(start2 >= n)
{
nums1[move++] = nums1[start1++];
continue;
}
if(start1 >= m + n)
{
nums1[move++] = nums2[start2++];
continue;
}
if(nums1[start1] < nums2[start2])
nums1[move++] = nums1[start1++];
else
nums1[move++] = nums2[start2++];
}
}