zoukankan      html  css  js  c++  java
  • [LeetCode]6. Merge Sorted Arrays合并排序数组

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

    Note:
    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 nums1and nums2 are m and n respectively.

    解法一:思路:合并后数组长度为m+n,为了不频繁移动数据,考虑从后往前确定合并后数组的每一个数,因此从后往前扫描两个排序数组进行处理。时间复杂度O(m+n)。

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            if(m == 0)
            {
                for(int i = 0; i < n; i++)
                    nums1[i] = nums2[i];
                return;
            }
            if(n == 0)
                return;
            
            int ind1 = m - 1;
            int ind2 = n - 1;
            
            for(int i = m + n - 1; i >= 0; i--)
            {
                if(ind1 >= 0 && ind2 >= 0)
                {
                    if(nums1[ind1] < nums2[ind2])
                    {
                        nums1[i] = nums2[ind2];
                        ind2--;
                    }
                    else
                    {
                        nums1[i] = nums1[ind1];
                        ind1--;
                    }
                }
                else if(ind1 < 0 && ind2 >= 0)
                {
                    nums1[i] = nums2[ind2];
                    ind2--;
                }
                else
                    break;
            }
        }
    };

    解法二:申请额外的O(m+n)的存储空间保存合并后数组,则从头往后遍历两个排序数组即可。时间复杂度O(m+n),空间复杂度O(m+n)。

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            if (m <= 0 && n <= 0) return;
            int a = 0, b = 0;
            int C[m + n];
            for (int i = 0; i < m + n; ++i) {
                if (a < m && b < n) {
                    if (nums1[a] < nums2[b]) {
                        C[i] = nums1[a];
                        ++a;
                    }
                    else {
                        C[i] = nums2[b];
                        ++b;
                    }
                }
                else if (a < m && b >= n) {
                    C[i] = nums1[a];
                    ++a;
                }
                else if (a >= m && b < n) {
                    C[i] = nums2[b];
                    ++b;
                }
                else return;
            }
            for (int i = 0; i < m + n; ++i) A[i] = C[i];
        }
    };
  • 相关阅读:
    PHP的跨域问题
    Linux常用命令
    搭建vagrant开发环境
    php 循环从数据库分页取数据批量修改数据
    Mac搭建pyhton+selenium+pycharm实现web自动化测试
    Mac 安装python 3.*新版本的详细步骤
    pycharm最新版本激活码(永久有效) python安装教程
    PHP操作redis 【转】
    php将图片存储在阿里云oss存储上
    Mac系统终端命令行不执行命令解决方法(command not found)
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4852637.html
Copyright © 2011-2022 走看看