Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. def merge(self, nums1, m, nums2, n):
  2.     """
  3.    :type nums1: List[int]
  4.    :type m: int
  5.    :type nums2: List[int]
  6.    :type n: int
  7.    :rtype: None Do not return anything, modify nums1 in-place instead.
  8.    """            
  9.     idxM = m - 1                        # the end index of nums1
  10.     idxN = n - 1                        # the end index of nums2
  11.     destination = m + n - 1             # we will write to nums1 from the end
  12.     while destination >= 0:
  13.         if idxM < 0:                            # if we only have nums2, copy those
  14.             nums1[destination] = nums2[idxN]
  15.             idxN -= 1
  16.         elif idxN < 0:                          # else if we only have nums1, copy those
  17.             nums1[destination] = nums1[idxM]
  18.             idxM -= 1
  19.         elif nums2[idxN] > nums1[idxM]:         # if num2 greater, write it at destination
  20.             nums1[destination] = nums2[idxN]
  21.             idxN -= 1
  22.         else:
  23.             # else num1 is greater, write it at destination and overwrite the existing location with min
  24.             nums1[destination], nums1[idxM] = nums1[idxM], -maxint-1  
  25.             idxM -= 1
  26.         destination -= 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement