LeetCode 88
88. Merge Sorted Arrayβ
Solutionβ
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.
"""
# Initialize pointers for nums1, nums2, and the end of nums1
i, j, k = m - 1, n - 1, m + n - 1
# Traverse from the end of both arrays and the merge them
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# If any elements are left in nums2, copy them to nums1
while j >= 0:
nums1[k] = nums2[j]
k -= 1
j -= 1
Time Complexityβ
nums1κ³Ό num2μ λͺ¨λ μμλ₯Ό μ΅λ ν λ²μ©λ§ λΉκ΅νλ―λ‘ λΉκ΅ νμλ μ΄λ€. λ°λΌμ μ 체 μκ° λ³΅μ‘λλ μ΄λ€.
Space Complexityβ
nums1μ λ΄λΆμμ λ³ν© μμ μ μννλ―λ‘ μΆκ° 곡κ°μ΄ νμνμ§ μλ€. λ°λΌμ κ³΅κ° λ³΅μ‘λλ μ΄λ€.
Commentβ
λ λ°°μ΄μ΄ μ λ ¬λμ΄ μμΌλ―λ‘ λ€μμλΆν° λΉκ΅νλ©΄μ μ±μ λ£μΌλ©΄ λλ€.