smj007

Untitled

Jul 30th, 2023
1,199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1.  
  2. """
  3. Approach 2 already demonstrates the best possible time
  4. complexity, O(n+m)\mathcal{O}(n + m)O(n+m), but still uses additional space.
  5. This is because the elements of array nums1 have to be stored somwhere so that
  6. they aren't overwritten.
  7.  
  8. So, what if instead we start to overwrite nums1 from the end, where
  9. there is no information yet?
  10.  
  11. The algorithm is similar to before, except this time we set p1 to point at index m - 1 of nums1,
  12. p2 to point at index n - 1 of nums2, and p to point at index m + n - 1 of nums1.
  13. This way, it is guaranteed that once we start overwriting the first m values in nums1,
  14. we will have already written each into its new position. In this way, we can eliminate the additional space.
  15.  
  16. class Solution:
  17.    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
  18.        """
  19.         Do not return anything, modify nums1 in-place instead.
  20.         """
  21.        
  22.        # Set p1 and p2 to point to the end of their respective arrays.
  23.        p1 = m - 1
  24.        p2 = n - 1
  25.    
  26.        # And move p backwards through the array, each time writing
  27.        # the smallest value pointed at by p1 or p2.
  28.        for p in range(n + m - 1, -1, -1):
  29.            if p2 < 0:
  30.                break
  31.            if p1 >= 0 and nums1[p1] > nums2[p2]:
  32.                nums1[p] = nums1[p1]
  33.                p1 -= 1
  34.            else:
  35.                nums1[p] = nums2[p2]
  36.                p2 -= 1
  37. """
  38.  
  39. class Solution:
  40.     def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
  41.         """
  42.        Do not return anything, modify nums1 in-place instead.
  43.        """
  44.  
  45.         p = m - 1
  46.         q = n - 1
  47.         r = m + n - 1
  48.  
  49.         while(p >=0 and q>=0):
  50.             if nums1[p] >= nums2[q]:
  51.                 nums1[r] = nums1[p]
  52.                 p = p - 1
  53.                 r = r - 1
  54.             else:
  55.                 nums1[r] = nums2[q]
  56.                 q = q - 1
  57.                 r = r - 1
  58.        
  59.         # what if there are corner cases; actually the corner cases won't exist
  60.         while (q >= 0):
  61.             nums1[r] = nums2[q]
  62.             r = r - 1
  63.             q = q - 1
Advertisement
Add Comment
Please, Sign In to add comment