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<int>& nums1, int m, vector<int>& 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<len1&&j<n){ if(nums1[i]<nums2[j]){ nums1[k++]=nums1[i++]; }else{ nums1[k++]=nums2[j++]; } } while(i<len1){ nums1[k++] = nums1[i++]; } while(j<n){ nums1[k++] = nums2[j++]; } } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45790433