zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】查找与排序题5:Merge Sorted Array

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Merge Sorted Array

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
    Note:
    • The number of elements initialized in nums1 and nums2 are m and n respectively.
    • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
    Example:
    Input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6], n = 3
     
    Output: [1,2,2,3,5,6]

    C++
     
    //问题:合并两个有序数组
    //方法一:开辟临时数组,通过比较两个有序数组,复制到临时数组中,再把排好序的数组复制回原数组
    /*class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
        {
           
            int i=0,j=0,k=0;
            vector<int> temp(m+n);
            while(i<m&&j<n)
            {
                temp[k++] = (nums1[i]<nums2[j])? nums1[i++]:nums2[j++];
            }
            while(i<m)
            {
                temp[k++] = nums1[i++];
            }
            while(j<n)
            {
                temp[k++] = nums2[j++];
            }
           
            int size = nums1.size();
            if(size >= (m+n))
                nums1 = temp;//将排序好元素赋值过去
            else
            {
                nums1.assign(temp.begin(), temp.begin()+size); //仅仅赋值部分元素
                cout<<"nums1空间不足!!"<<endl;
            }
           
        }
    };*/
    //方法二:从后往前扫描,依次复制(未开辟额外空间,效率更优)
    class Solution
    {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
        {
            int i=m-1,j=n-1,k=nums1.size()-1;//从后往前扫描, i,j分别指向有序数组末尾,k指向nums1空间的末尾
            while(i>=0 && j>=0)
            {
                nums1[k--] = (nums1[i] > nums2[j])? nums1[i--]:nums2[j--];
            }
            while(j >= 0) //将nums2剩余元素复制过去
            {
                nums1[k--] = nums2[j--];
            }
           
        }
    };
     
     
  • 相关阅读:
    ABP 前端 组件之间传递参数的几种方式
    angular Form 自定义验证
    Docker 启用失败 failed to start docker Application container Engin
    C# 委托与事件
    c# Application.DoEvents()
    c# 泛型
    Ubuntu如何挂载U盘
    jdk1.8 List根据时间字段倒序排序
    yarn安装模块报错:check python checking for Python executable "python2" in the PATH
    yarn : 无法加载文件 C:\Users\Administrator\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本。
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225930.html
Copyright © 2011-2022 走看看