leetcode-88-merge-sorted-array
題目
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 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 |
Example 2
1 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 |
Example 3
1 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 |
解釋題目
給你兩個 array,nums1 和 nums2,兩個 array 都是「由小排到大」的排列方式。nums1 有 m 個數字,nums2 有 n 個數字。題目要求要把 nums1 跟 num2 結合成一個 array,而且要是合併在 nums1 中。也就是說, nums1 的長度其實是 m + n,nums1 已經先把 nums2 要的空間開出來,用 0 表示。最後,函式不用回傳任何東西,題目會直接驗證 nums1 的結果。
思路
這是一個很標準的 雙指針 題目。這題有幾個很重要的想法:
- 要從 nums1 跟 nums2 的 m 跟 n 的位置下手,因為這兩個 array 都是升冪排列,所以要從最大的位置往前排回來。
- m 跟 n 也是代表不同的 指針。
- 接著,就是比較 nums1 中 m 位置的值,以及 nums2 中 n 的值。較大的值,要對 nums1 進行「補位」。
- 「補位」的意思就是,把較大的值,移到 nums1 最後一個位置,也就是 m + n 的地方。
- 補位完的指針,假設是 n,n 就要往前走一步。
- 結束的條件是: n 補完的時候,只要 n 還有數字,就要繼續補位
注意: 另一個條件是
m > 0
才要持續比較。如果 m 已經是 0 的話,就只要把 nums2 補完就好。這個條件沒有加上的話,m - 1 會回到 nums1 中 m + n 的位置 ( 也就是 m = -1 ),無限輪迴,直到 m 超出 nums1 的範圍,就會報錯。
圖像拆解
程式碼
1 | class Solution: |