1. 程式人生 > >[Leetcode] Merge Sorted Array

[Leetcode] Merge Sorted Array

amp from sum esp 題解 eat integer 合並 需要

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尾部即可,這樣就不需要額外的空間保存歸並的結果。

[Leetcode] Merge Sorted Array