Skip to main content

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의 λͺ¨λ“  μš”μ†Œλ₯Ό μ΅œλŒ€ ν•œ λ²ˆμ”©λ§Œ λΉ„κ΅ν•˜λ―€λ‘œ 비ꡐ νšŸμˆ˜λŠ” O(m+n)O(m + n)이닀. λ”°λΌμ„œ 전체 μ‹œκ°„ λ³΅μž‘λ„λŠ” O(m+n)O(m + n)이닀.

Space Complexity​

nums1의 λ‚΄λΆ€μ—μ„œ 병합 μž‘μ—…μ„ μˆ˜ν–‰ν•˜λ―€λ‘œ μΆ”κ°€ 곡간이 ν•„μš”ν•˜μ§€ μ•Šλ‹€. λ”°λΌμ„œ 곡간 λ³΅μž‘λ„λŠ” O(1)O(1)이닀.

Comment​

두 배열이 μ •λ ¬λ˜μ–΄ μžˆμœΌλ―€λ‘œ λ’€μ—μ„œλΆ€ν„° λΉ„κ΅ν•˜λ©΄μ„œ μ±„μ›Œ λ„£μœΌλ©΄ λœλ‹€.