From f216b0c7020e03d98d2a7ed4d264f4f607ebf95f Mon Sep 17 00:00:00 2001 From: Gabriel Donnan <47415809+gabedonnan@users.noreply.github.com> Date: Mon, 5 Jun 2023 20:46:56 +0100 Subject: [PATCH] Create merge-arrays.py efficient solution, additionally the arrays can be added together and then sorted via .sort for the same effect, this is much slower however. --- merge-arrays.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 merge-arrays.py diff --git a/merge-arrays.py b/merge-arrays.py new file mode 100644 index 0000000..35609ab --- /dev/null +++ b/merge-arrays.py @@ -0,0 +1,17 @@ +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. + """ + p1 = m - 1 + p2 = n - 1 + p_main = m + n - 1 # Pointer to array location of next addition + # Pointers start from the back to avoid shifting the array along + while p2 >= 0: # Iterate until p2 is negative, this means both p1 and p2 are exhausted + if p1 >= 0 and nums1[p1] > nums2[p2]: + nums1[p_main] = nums1[p1] + p1 -= 1 + else: + nums1[p_main] = nums2[p2] + p2 -= 1 + p_main -= 1