leetcode笔记:Merge Sorted Array

数组合并算法
本文介绍了一种高效的数组合并方法,通过从后向前遍历两个已排序数组,并将较大元素放入目标数组末尾,实现O(m+n)时间复杂度的合并操作。

一.题目描写叙述

这里写图片描写叙述

二.解题技巧

这道题不存在复杂的分析过程和边界条件。假设单纯得考虑从小到大地将两个数组进行合并的话。每次在num1中插入一个数的话,须要将后面的元素都向后移动一位。这样。整个处理过程的时间复杂度为O(m*n)。

因为两个数组的元素的个数是知道的。同一时候,合并后的数组也是递增排序的,也就是说,排序之后的数组的最大值是放在最后面的。因此,我们能够从后往前遍历,也就是将最大值放在第一个数组的m+n-1位置。然后将次最大值放在m+n-2位置,依次类推。这样在将元素放置到合适位置的时候,就不须要移动元素,这种方法的时间复杂度为O(m+n)。

三.演示样例代码

// 时间复杂度O(m+n),空间复杂度O(1)
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int ia = m - 1, ib = n - 1, icur = m + n - 1;
        while (ia >= 0 && ib >= 0) {
            A[icur--] = A[ia] >= B[ib] ?

A[ia--] : B[ib--]; } while (ib >= 0) { A[icur--] = B[ib--]; } } };

// 使用STL
#include <iostream>  
#include <vector>  

using std::vector;

class Solution
{
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
    {
        int ResultIndex = m + n - 1;
        m--;
        n--;
        while (m >= 0 || n >= 0)
        {
            if (m < 0)
            {
                nums1[ResultIndex--] = nums2[n--];
                continue;
            }

            if (n < 0)
            {
                nums1[ResultIndex--] = nums1[m--];
                continue;
            }

            if (m >= 0 && n >= 0)
            {
                if (nums1[m] > nums2[n])
                {
                    nums1[ResultIndex--] = nums1[m--];
                    continue;
                }
                else
                {
                    nums1[ResultIndex--] = nums2[n--];
                    continue;
                }
            }
        }
    }
};

转载于:https://www.cnblogs.com/clnchanpin/p/7048433.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值