• Leetcode 88. Merge Sorted Array


    88. Merge Sorted Array

    • Total Accepted: 109369
    • Total Submissions: 359044
    • Difficulty: Easy

    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 nums1 and nums2 are m and n respectively.

     
     
     
    思路:过程中,不能改变nums1的规模,所以前插法是不可行的。要从最后的坐标开始替换。文末有错误的前插法。

     
     
    代码:
     1 //过程中,不能改变nums1的规模,所以前插法是不可行的。要从最后的坐标开始替换。
     2 class Solution {
     3 public:
     4     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
     5         int i=m-1,j=n-1,tar=m+n-1;
     6         while(i>=0&&j>=0){
     7             nums1[tar--]=nums1[i]>nums2[j]?nums1[i--]:nums2[j--];
     8         }
     9         while(j>=0){
    10             nums1[tar--]=nums2[j--];
    11         }
    12     }
    13 };

    简化后:

    1 class Solution {
    2 public:
    3     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    4         int i=m-1,j=n-1,tar=m+n-1;
    5         while(j>=0){
    6             nums1[tar--]=i>=0&&nums1[i]>nums2[j]?nums1[i--]:nums2[j--];
    7         }
    8     }
    9 };
     
    错误的前插法:
     1 class Solution {
     2 public:
     3     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
     4         int i,j;
     5         for(i=0,j=0;i<m&&j<n;i++){
     6             if(nums1[i]>nums2[j]){
     7                 nums1.insert(nums1.begin()+i,nums2[j++]);
     8                 m++;
     9             }
    10         }
    11         if(i>=m){
    12             while(j<n){
    13                 nums1.insert(nums1.begin()+i,nums2[j++]);
    14             }
    15         }
    16     }
    17 };
     
     
  • 相关阅读:
    Windows上安装PyV8
    Windows鼠标右键菜单添加SublimeText打开选项
    Windows使用Python虚拟环境
    Windows同时安装Python2和Python3
    Windows使用Cmder
    Visual Studio Code配置
    Windows 10使用Tesseract-OCR出现WindowsError: [Error 2]
    用pymysql代替MySQLdb
    使用python来搞定redis的订阅功能
    来写一个最基本的装饰器吧!
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5677998.html
Copyright © 2020-2023  润新知