Merge Sorted Array
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.
解題思路:
這道題與合並排序差不多,唯一不同的是不可以申請額外的空間。注意到第一個數組的實際空間長度是大於兩個數組長度之和的,因此,我們可以先把第一個數組的元素平移至末尾,然後按合並排序的步驟合並即可。
class Solution { public: void merge(vector& nums1, int m, vector & nums2, int n) { //首先將nums1的元素後移至末尾 int len1=nums1.size(); for(int i=1; i<=m; i++){ nums1[len1-i] = nums1[m-i]; } int k=0; int i = len1 - m; int j = 0; while(i