• [Leetcode] Merge Sorted Array


    Merge Sorted Array 题解

    题目来源:https://leetcode.com/problems/merge-sorted-array/description/


    Description

    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.

    Solution

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int i = m - 1, j = n - 1, k = m + n - 1;
            while (i >= 0 && j >= 0) {
                nums1[k--] = nums1[i] >= nums2[j] ? nums1[i--] : nums2[j--];
            }
            while (j >= 0) {
                nums1[k--] = nums2[j--];
            }
        }
    };
    

    解题描述

    这道题题意是,给出两个排好序的数组nums1nums2,分别包含mn个数字,nums1总的空间不小于m + n,要求合并两个数组,将结果存在nums1中。也就是说,空余的空间一开始是在nums1数组的尾部,算法就是从大到小进行归并,将结果依次插入到nums1尾部即可,这样就不需要额外的空间保存归并的结果。

  • 相关阅读:
    regedit注册表
    Environment应用
    VMI帮助类
    Image帮助类
    asp.net core+Postman
    printf和cout的区别详述
    C++指针
    Qt button和buttons区别
    visual studio收函数
    编译警告
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8421858.html
Copyright © 2020-2023  润新知