首页 > 其他 > 详细

89. Merge Sorted Array

时间:2016-09-11 06:47:49      阅读:199      评论:0      收藏:0      [点我收藏+]

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来定边界条件发现很麻烦,转而用nums2,需要考虑的条件少了很多。if condition的前后转化要多注意。

 

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--;
            }
        }
    }
}

 

89. Merge Sorted Array

原文:http://www.cnblogs.com/Machelsky/p/5860899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!