[LeetCode]6. Merge Sorted Arrays合并排序数组
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 nums1and nums2 are m and n respectively.
解法一:思路:合并后数组长度为m+n,为了不频繁移动数据,考虑从后往前确定合并后数组的每一个数,因此从后往前扫描两个排序数组进行处理。时间复杂度O(m+n)。
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if(m == 0) { for(int i = 0; i < n; i++) nums1[i] = nums2[i]; return; } if(n == 0) return; int ind1 = m - 1; int ind2 = n - 1; for(int i = m + n - 1; i >= 0; i--) { if(ind1 >= 0 && ind2 >= 0) { if(nums1[ind1] < nums2[ind2]) { nums1[i] = nums2[ind2]; ind2--; } else { nums1[i] = nums1[ind1]; ind1--; } } else if(ind1 < 0 && ind2 >= 0) { nums1[i] = nums2[ind2]; ind2--; } else break; } } };
解法二:申请额外的O(m+n)的存储空间保存合并后数组,则从头往后遍历两个排序数组即可。时间复杂度O(m+n),空间复杂度O(m+n)。
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if (m <= 0 && n <= 0) return; int a = 0, b = 0; int C[m + n]; for (int i = 0; i < m + n; ++i) { if (a < m && b < n) { if (nums1[a] < nums2[b]) { C[i] = nums1[a]; ++a; } else { C[i] = nums2[b]; ++b; } } else if (a < m && b >= n) { C[i] = nums1[a]; ++a; } else if (a >= m && b < n) { C[i] = nums2[b]; ++b; } else return; } for (int i = 0; i < m + n; ++i) A[i] = C[i]; } };