LintCode 6. Merge Two Sorted Arrays

本文介绍了一个简单的算法问题:合并两个已排序的整数数组。通过使用双指针技术,逐个比较并合并两个数组,最终形成一个新的有序数组。此方法不需要额外的空间复杂度,适用于直接合并两个有序数组的场景。

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

LintCode 6. Merge Two Sorted Arrays


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

题意理解

很简单的题,没有要求不能使用额外空间,就用两个指针分别从头往后比较A,B两个数组,一个个将数组组建起来。

class Solution {
public:
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
        int pa = 0;
        int pb = 0;
        vector<int> result;
        while (pa < A.size() && pb < B.size()) {
            if (A[pa] <= B[pb]) {
                result.push_back(A[pa++]);
            } else {
                result.push_back(B[pb++]);
            }
        }
        while (pa < A.size()) {
            result.push_back(A[pa++]);
        }
        while(pb < B.size()) {
            result.push_back(B[pb++]);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值