From 9a3e4a94c6422395a42abd1d12f69f1a7f3c9668 Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Fri, 8 Mar 2024 19:02:46 +0000 Subject: [PATCH] Solve 88. Merge Sorted Array --- python/88_merge_sorted_array.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 python/88_merge_sorted_array.py diff --git a/python/88_merge_sorted_array.py b/python/88_merge_sorted_array.py new file mode 100644 index 0000000..3dfdd2d --- /dev/null +++ b/python/88_merge_sorted_array.py @@ -0,0 +1,27 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + current = m + n - 1 # Pointer where we are currently inserting elements + left = m - 1 # Pointer to the largest remaining element in nums1 + right = n - 1 # Pointer to the largest remaining element in nums2 + + while left >= 0 and right >= 0: + if nums1[left] > nums2[right]: + nums1[current] = nums1[left] + left -= 1 + else: + nums1[current] = nums2[right] + right -= 1 + current -= 1 + + while left >= 0: + nums1[current] = nums1[left] + left -= 1 + current -= 1 + + while right >= 0: + nums1[current] = nums2[right] + right -= 1 + current -= 1