題目
原題頁面:https://leetcode.com/problems/merge-sorted-array/
題目型別:Array, Two Pointers
難度評價:Easy
類似題目:(E) Merge Two Sorted Lists
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.
分析
將一個有序陣列B合併到另一個有序陣列A。這題如果從陣列頭開始合併,則每一次都要整體移動陣列A後面的元素,顯然不是理想的方法。一種巧妙的做法是從兩個陣列尾部開始合併,這樣就避免了大面積的陣列元素移動。
程式碼
1 | class Solution: |
