两数组合并

空间复杂度O(n)方式

数组1:{1, 3, 5, 7, 9}
数组2:{2, 5, 7, 9, 13}
合并后:[1,2,3,5,5,7,7,9,9,13]

/**
 * 两个数组合并
 */
public class ArrayMerge {


    public static void main(String[] args) {
        int[] sum1 = {1, 3, 5, 7, 9};
        int[] sum2 = {2, 5, 7, 9, 13};
        merge(sum1, sum1.length, sum2, sum2.length);
        System.out.println(JSONObject.toJSONString(newNums));
    }

    private static List<Integer> newNums;

    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        newNums = new ArrayList<Integer>(m + n);
        int index1 = 0;
        int index2 = 0;
        while (index1 < m || index2 < n) {
            if (index1 < m && index2 < n) {
                int mEl = nums1[index1];
                int nEl = nums2[index2];
                if (mEl > nEl) {
                    newNums.add(nEl);
                    index2++;
                } else {
                    newNums.add(mEl);
                    index1++;
                }
                continue;
            }
            if (index1 < m) {
                newNums.add(nums1[index1]);
                index1++;
                continue;
            } else {
                newNums.add(nums2[index2]);
                index2++;
            }
        }
    }
}

利用成型工具:

public void merge(int[] nums1, int m, int[] nums2, int n) {
        /**
         * 1:将nums2拷贝到nums1中
         * 2:从nums2下标0开始拷贝
         * 3:nums1
         * 4:nums1的第几个元素开始依次存放nums2
         * 5:nums2的长度
         */
        System.arraycopy(nums2,0,nums1,m,n);
        Arrays.sort(nums1);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值