smj007

Untitled

Jul 30th, 2023
1,181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. """
  2. Time complexity: O(n+m)
  3.  
  4. We are performing n+2⋅mn + 2 \cdot mn+2⋅m reads and n+2⋅mn + 2 \cdot mn+2⋅m writes. Because constants are ignored in Big O notation, this gives us a time complexity of O(n+m)\mathcal{O}(n + m)O(n+m).
  5.  
  6. Space complexity: O(m)
  7. We are allocating an additional array of length mmm.
  8. """
  9.  
  10. class Solution:
  11.     def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
  12.         """
  13.        Do not return anything, modify nums1 in-place instead.
  14.        """
  15.  
  16.         nums3 = nums1[:m]
  17.         first = 0
  18.         second = 0
  19.         third = 0
  20.  
  21.         while (first < n+m):
  22.             if ((second <n and third < m) and nums3[third] <= nums2[second]) or second>=n:
  23.                 nums1[first] = nums3[third]
  24.                 third += 1
  25.             elif ((second < n and third < m) and nums3[third] > nums2[second]) or first>=m:
  26.                 nums1[first] = nums2[second]
  27.                 second += 1
  28.             first += 1
  29.  
  30.  
Advertisement
Add Comment
Please, Sign In to add comment