LeetCode88. Merge Sorted Array(模拟)
- Easy
- Accepted:318,463
- Submissions:921,821
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
链接
https://leetcode.com/problems/merge-sorted-array/
题意
给定两个有序的数组nums1和nums2,将nums2合并到nums1中并保持有序,保证nums1有足够的空间来存储两个数组的元素。
题解
- 两个有序数组的合并其实就是归并排序中的合并操作。从头到尾遍历的话,就需要再开一个辅助数组,因为直接操作的话num1数组中的元素可能会被覆盖。时间复杂度$O(n+m)$,空间复杂度$O(n+m)$
- 可以选择从后往前遍历,这样就无须额外的辅助数组,时间复杂度$O(n+m)$,空间复杂度$O(1)$,刚好可以用上题目中的特殊条件
代码
- Runtime: 4 ms, faster than 86.91% of C++ online submissions for Merge Sorted Array.
- Memory Usage: 790.5 KB, less than 16.20% of C++ online submissions for Merge Sorted Array.
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = 0, j = 0, tmp;
vector <int> numsAns; // 辅助数组
numsAns.clear();
while (i < m && j < n)
{
tmp = nums1[i] <= nums2[j] ? nums1[i++] : nums2[j++];
numsAns.push_back(tmp);
}
while (i < m)
numsAns.push_back(nums1[i++]);
while (j < n)
numsAns.push_back(nums2[j++]);
for (int k = 0; k < m + n; ++k) // 还原
nums1[k] = numsAns[k];
}
};
- Runtime: 4 ms, faster than 86.91% of C++ online submissions for Merge Sorted Array.
- Memory Usage: 774.1 KB, less than 85.65% of C++ online submissions for Merge Sorted Array.
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--];
}
};
The end.
2019年2月2日 星期六