Advertisement
smj007

Merge sorted arrays (in-place)

Aug 11th, 2024
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. class Solution:
  2.     def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
  3.         """
  4.        Do not return anything, modify nums1 in-place instead.
  5.        """
  6.  
  7.         first = m - 1
  8.         second = n - 1
  9.         third = m + n - 1
  10.  
  11.         while(first >= 0 and second >=0):
  12.             if nums1[first] >= nums2[second]:
  13.                 nums1[third] = nums1[first]
  14.                 third -= 1
  15.                 first -= 1
  16.             else:
  17.                 nums1[third] = nums2[second]
  18.                 third -= 1
  19.                 second -= 1
  20.  
  21.         while(second >= 0):
  22.             nums1[third] = nums2[second]
  23.             second -= 1
  24.             # made the mistake of not decreasing the third pointer
  25.             third -= 1
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement