Python solution O(m+n)


  • 0
    A

    '''

    class Solution(object):
    def merge(self, nums1, m, nums2, n):
    """
    :type nums1: List[int]
    :type m: int
    :type nums2: List[int]
    :type n: int
    :rtype: void Do not return anything, modify nums1 in-place instead.
    """
    lenArr1 = m
    lenArr2 = n

        # for i in range(len(nums2)):
        #     nums1.append(0)
    
        k = m + n - 1
        i = m - 1
        j = n - 1
    
        while k >= 0:
            if j >= 0 and i >= 0:
                if nums1[i] > nums2[j]:
                    nums1[k] = nums1[i]
                    i -= 1
                    k -= 1
    
                else:
                    nums1[k] = nums2[j]
                    j -= 1
                    k -= 1
            else:
                if i >= 0:
                    nums1[k] = nums1[i]
                    k -= 1
                    i -= 1
                elif j >= 0:
                    nums1[k] = nums2[j]
                    k -= 1
                    j -= 1
    

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.