Merged Sorted Array

问题描述:两个排好序的数组nums1,与nums2。要将这两个数组一起排序存储到nums1中,nums1中有n个元素,nums2中有m个元素。nums1的长度比大于等于m+n。


解决:题目要求使用nums1来存储而不能新建一个空的数组来保存。如果nums1从nums[0]开始从前往后保存新排序的元素,一定会出现新元素将原始元素覆盖的问题。

好在nums1的长度足够,从nums1[n]开始一直到最后都是空的。如果我们将新的元素从后往前填入nums1,便不会出现上述问题。


/*
 * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
 * 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.
 */
public class MergeSortedArray {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if(nums1 == null|nums2 == null)
                return;
        
        int index1 = m-1;
        int index2 = n-1;
        int index3 = m+n-1;
        while(index1 >=0 && index2 >=0) {
                if(nums1[index1] >= nums2[index2]) {
                        nums1[index3--] = nums1[index1--];
                } else {
                        nums1[index3--] = nums2[index2--];
                }
        }
        while(index2>=0) {
                nums1[index3--] = nums2[index2--];
        }
    }
}

如果出现一方小于 0 的情况,比如index1小于 0 ,表示nums1遍历结束,nums2剩余的所有元素均比nums1 [ 0 ] 小,此时只要把nums2剩余的所有元素放到新数组的

开头即可。当index2小于0,表示nums1剩余的所有元素最小,需要放到新数组的开头,但是由于新数组就是使用nums1来保存,所以不再需要额外的赋值操作。

此算法的时间复杂度为o(m+n),空间复杂度为o(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值