题目描述
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.
把两个有序的数组融合到一起,使融合后的数组仍然有序。并且数组1的长度是足够容纳数组2的。
代码及注释
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
// l1和l2分别是nums1和nums2当前比较的指针,lcur是当前插入位置
int l1 = m-1, l2 = n-1, lcur = m+n-1;
// 一直比较,直到1或2有一个到头,2先到头无所谓,正好结束
while(l1 >= 0 && l2 >=0){
// 注意后置--++
nums1[lcur--] = nums1[l1] >= nums2[l2] ? nums1[l1--] : nums2[l2--];
}
// 1先到头单独考虑,把nums2剩余的插入前面
while(l2 >= 0){
nums1[lcur--] = nums2[l2--];
}
}
};
分析
"""
Created on Tue Jun 1 16:05:38 2017
@author: mml
@email: mmlin.nju@gmail.com
"""