Merge Sorted Array

本文介绍了一种合并两个已排序整数数组的方法,并提供了一个具体的Java实现案例。文章探讨了如何优化算法以应对一个数组非常大而另一个非常小的情况,通过使用二分查找技术来提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Merge Sorted Array

Merge two given sorted integer array A and B into a new sorted integer array.

Example

A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]

Challenge

How can you optimize your algorithm if one array is very large and the other is very small?

Solution:

 public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
        ArrayList<Integer> result = new ArrayList<Integer>(); 
        if (A == null || A.size() == 0) {
            return (new ArrayList<Integer>(B));
        } else if (B == null || B.size() == 0) {
            return (new ArrayList<Integer>(A));
        }
        int aIndex = 0;
        int bIndex = 0;
        int a;
        int b;
        if (A.size() > B.size()) {
            int index = bs(A, B.get(0));
            while (aIndex < index) {
                result.add(A.get(aIndex++));
            }
        } else {
            int index = bs(B, A.get(0));
            while (bIndex < index) {
                result.add(B.get(bIndex++));
            }
        }
        while (aIndex < A.size() && bIndex < B.size()) {
            a = A.get(aIndex);
            b = B.get(bIndex);
            if (a < b) {
                result.add(a);
                aIndex++;
            } else {
                result.add(b);
                bIndex++;
            }
        }
        while (aIndex < A.size()) {
            result.add(A.get(aIndex++));
        }
        while (bIndex < B.size()) {
            result.add(B.get(bIndex++));
        }
        return result;
    }
    private int bs(ArrayList<Integer> A, int target) {
        int start = 0;
        int end = A.size() - 1;
        int mid;
        while (start + 1 < end) {
            mid = start + ((end - start) >> 1);
            if (A.get(mid) == target) {
                return mid;
            } else if (A.get(mid) > target) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (A.get(end) <= target) {
            return end;
        }
        if (A.get(start) <= target) {
            return start;
        }
        return 0;
    }

思路:

1. 依次比较,剩下的全部加进去

2. 长短list。使用二分搜索,在长list里找到短list中的最小值。返回和最小值相等或者小于最小值的index。将长list在index之前的全部加入到result中,剩下的一次比较。

Note:

ArrayList与vector都是以数组形式存储,LinkedList是链表形式存储。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值