0088. Merge Sorted Array
Easy | Array + Two Pointers | 16ms (98.22%), 13.3 MB (94.73%)
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.class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# (base case)
if n == 0: return
if m == 0:
for i in range(n): nums1[i] = nums2[i]
# ==================================================
# Array + Three Pointers (Start from End) =
# ==================================================
# time : O(m+n)
# space : O(1)
p1, p2, placeP = m - 1, n - 1, m + n - 1
while placeP >= 0:
if p2 < 0: return
if p1 >= 0 and nums1[p1] >= nums2[p2]:
nums1[placeP] = nums1[p1]
p1 -= 1
else:
nums1[placeP] = nums2[p2]
p2 -= 1
placeP -= 1Last updated