Merge Sorted Array

Problem: Merge Sorted Array

The solution is quite simple. We just insert every number in second array into an appropriate position in the first array.

Code in Python:

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.
        """
        nums1[:] = nums1[:m]
        nums2[:] = nums2[:n]
        i = 0
        for num in nums2:
            while i < len(nums1) and nums1[i] < num: i += 1
            nums1.insert(i, num)

results matching ""

    No results matching ""