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.
这道题很简单,两个数组从前面开始比较会覆盖后面的,所以选择从后面开始比较。题目已给了nums1的大小是大于等于m+n的,所以不用关心空间问题(假设空间没给可以用resize函数重新分配),唯一要注意是边界条件的判断。
贴出C++实现:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { // nums1.resize(m+n); int lenth=m+n-1; if(m==0) { nums1=nums2; return; } if(n==0) { return; } int i,j; for(i=m-1,j=n-1;i>=0&&j>=0;) { if(nums1[i]>=nums2[j]) { nums1[lenth--]=nums1[i]; i--; } else { nums1[lenth--]=nums2[j]; j--; } } while(j>=0) { nums1[j]=nums2[j]; j--; } }