题意:给你两个已经排好升序的数组,让你把他们合并成一个升序数组,只能合并在原有的数组上。
思路:如果从数组前端开始更新的话可能会覆盖数组原先的值,所以要从合并后的数组的末端开始更新,
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int t = m+n-1,i = m-1,j = n-1;
if(m==0)
{
nums1 = nums2;
return ;
}
if(n==0)
return ;
while(j>=0)
{
if(i<0)
nums1[t--] = nums2[j--];
else
nums1[t--] = nums1[i]>nums2[j]?nums1[i--]:nums2[j--];
}
}
};