공대생의 비망록

[LeetCode][Easy] Merge Sorted Array Python 풀이 본문

Programming Language/Python

[LeetCode][Easy] Merge Sorted Array Python 풀이

myungsup1250 2026. 2. 7. 23:27
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.
        """
        if n == 0:
            return
        if m == 0:
            # nums1 = nums2 # This will not meet the in-place requirement
            for i in range(n): # To meet the in-place requirement
                nums1[i] = nums2[i]
            return

        i = m - 1; j = n - 1
        while i >= 0 and j >= 0:
            if nums1[i] > nums2[j]:
                nums1[i+j+1] = nums1[i]
                i -= 1
            else:
                nums1[i+j+1] = nums2[j]
                j -= 1

        while j >= 0:
            nums1[j] = nums2[j]
            j -= 1

        return
Comments