🖋

LeetCode 88. Merge Sorted Array (Python3)

に公開

はじめに

LeetCode 「88. Merge Sorted Array」の問題を Python3 で解きました。

問題

https://leetcode.com/problems/merge-sorted-array/description/

問題文

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

和訳
2つの整数配列nums1nums2が与えられます。これらは非減少順にソートされており、2つの整数mとnがそれぞれnums1nums2の要素数を表します。

nums1nums2を非減少順にソートされた単一の配列にマージしてください。

最終的なソート済み配列は関数から返すのではなく、配列nums1内に格納してください。このため、nums1の長さはm + nであり、最初のm要素がマージ対象の要素を示し、最後のn要素は0に設定され無視されます。nums2の長さはnです。

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

制約

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -109 <= nums1[i], nums2[j] <= 109

解答1(ソート)

nums1の有効部分とnums2を結合してソートするシンプルなアプローチです。
解答2よりは効率が悪くなります。

以下の手順で処理します。

  1. nums1の有効部分を切り出す
  2. nums2と結合する
  3. sort()
  4. 結果をnums1にコピー

コード

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        nums1[:] = sorted(nums1[:m] + nums2)

計算量

  • 時間的計算量:O((m+n) log(m+n))
  • 空間的計算量:O(m+n)

解答2(2ポインタ)

2ポインタのアプローチでより効率的な実装が可能です。
num1の末尾から大きい数値を順番に埋めていきます。

今回の問題では、nums1の後ろに空きがあります。(0で埋まっている)
先頭から埋めていくと元の要素を壊してしまいますが、末尾から埋めていくことで安全に上書きすることが可能です。

コード

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        p1 = m - 1 # nums1の有効部分の末尾
        p2 = n - 1 # nums2の末尾
        p = m + n - 1 # nums1全体の末尾

        while p2 >= 0:
            if p1 >= 0 and nums1[p1] > nums2[p2]:
                nums1[p] = nums1[p1]
                p1 -= 1
            else:
                nums1[p] = nums2[p2]
                p2 -= 1
            p -= 1

num1nums2の要素から大きい方を nums1[p] に入れて、ポインタを動かします。

計算量

  • 時間的計算量:O(m+n)
    • 1回ずつしか走査しない
  • 空間的計算量:O(1)
    • 追加のメモリ不要
GitHubで編集を提案

Discussion