題目

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.

Example 1

1
2
3
4
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.

Example 2

1
2
3
4
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].

Example 3

1
2
3
4
5
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.

解釋題目

給你兩個 array,nums1 和 nums2,兩個 array 都是「由小排到大」的排列方式。nums1 有 m 個數字,nums2 有 n 個數字。題目要求要把 nums1 跟 num2 結合成一個 array,而且要是合併在 nums1 中。也就是說, nums1 的長度其實是 m + n,nums1 已經先把 nums2 要的空間開出來,用 0 表示。最後,函式不用回傳任何東西,題目會直接驗證 nums1 的結果。

思路

這是一個很標準的 雙指針 題目。這題有幾個很重要的想法:

  1. 要從 nums1 跟 nums2 的 m 跟 n 的位置下手,因為這兩個 array 都是升冪排列,所以要從最大的位置往前排回來。
  2. m 跟 n 也是代表不同的 指針
  3. 接著,就是比較 nums1 中 m 位置的值,以及 nums2 中 n 的值。較大的值,要對 nums1 進行「補位」。
  4. 「補位」的意思就是,把較大的值,移到 nums1 最後一個位置,也就是 m + n 的地方。
  5. 補位完的指針,假設是 n,n 就要往前走一步。
  6. 結束的條件是: n 補完的時候,只要 n 還有數字,就要繼續補位

注意: 另一個條件是 m > 0 才要持續比較。如果 m 已經是 0 的話,就只要把 nums2 補完就好。這個條件沒有加上的話,m - 1 會回到 nums1 中 m + n 的位置 ( 也就是 m = -1 ),無限輪迴,直到 m 超出 nums1 的範圍,就會報錯。

圖像拆解

步驟拆解 1


步驟拆解 2


步驟拆解 3


步驟拆解 4

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
index = m + n - 1
while n > 0:
if m > 0 and nums1[m - 1] > nums2[n - 1]:
nums1[index] = nums1[m - 1]
m = m - 1
else:
nums1[index] = nums2[n - 1]
n = n - 1
index = index - 1