Merge Sorted Array

 

88. Merge Sorted Array

Solution

Reference

  1. Notice that the empty slots are at the end of the array.

  2. Start from the end of the array and travel towards the beginning of the array.

def merge(self, nums1, m, nums2, n):
    """
    :type nums1: List[int]
    :type m: int
    :type nums2: List[int]
    :type n: int
    :rtype: None Do not return anything, modify nums1 in-place instead.
    """
    i, j = m-1, n-1
    end = m + n - 1
    while i >= 0 and j >= 0:
        if nums1[i] < nums2[j]:
            nums1[end] = nums2[j]
            j -= 1
        else:
            nums1[end] = nums1[i]
            i -= 1
        end -= 1
    while j >= 0:
        nums1[end] = nums2[j]
        end -= 1
        j -= 1

    return nums1