zoukankan      html  css  js  c++  java
  • 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 };
     
     
  • 相关阅读:
    字符串比较
    LOOP AT SCREEN
    Trunc的日期用法
    【ABAP】SELECT-ENDSELECT尽量不要用
    【转】Abap For all entries in 使用
    01如何创建sequence:
    abap --MOVE-CORRESPONDING
    Abap 常用变量
    StringBuffer的用法
    Spring事务的传播方式
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5677998.html
Copyright © 2011-2022 走看看