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足够大,所以从nums1末尾开始存数。

假设nums1, n个数。

nums2,m个数。

那么总个数m+n. 我们会想,如果这样从末尾插入比较会不会影响num1本身的arrary。用极端情况就可以知道如果nums1全部小于nums2,那么nums2全部填充了n,不会影响到nums1里面任何一个array。因此任何其他情况都不会影响到nums1的array。然后我们会想用哪个长度来限制呢,很明显是nums2的长度,因为我们其实是往nums1里面插入nums2的数字。因此若nums2完成插入,可能会出现nums1还有剩余,这时候我们就不需要对nums1做任何操作,因此选nums2长度。

 

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if(n==0)
        {
            return;
        }
        int l1=m-1;
        int l2=n-1;
        int total=m+n-1;
        for(int i=total;i>=0;i--)
        {
            if(l2>=0&&l1>=0&&nums1[l1]<=nums2[l2]||l1<0)
            {
                nums1[i]=nums2[l2];
                l2--;
            }
            else
            {
                nums1[i]=nums1[l1];
                l1--;
            }
        }
    }
}

 

posted on 2016-09-11 04:02  Machelsky  阅读(164)  评论(0)    收藏  举报