Skip to content

Instantly share code, notes, and snippets.

@Josephchinedu
Created May 14, 2022 15:12
Show Gist options
  • Save Josephchinedu/ab5ec0745b0274c14f65e1539a7deda5 to your computer and use it in GitHub Desktop.
Save Josephchinedu/ab5ec0745b0274c14f65e1539a7deda5 to your computer and use it in GitHub Desktop.
merge_sorted_array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
The number of elements initialized in nums1 and nums2 are m and n respectively.
Steps:
1. create a variable that will hold the new value of nums1.
Because, we're selecting the numbers in nums1 and leaving out the zeroes.
"m" is always the length of numbers in nums1.
our new nums1 will now be.
new_list = nums[0:m]
2. turn the whole of nums1 into an empty list, because the instruction said we should not return anythin but modify nums1 in-place
instead.
nums1[:] = []
3. run a loop that will continue running as long as there's value in new_list or nums2.
Inside the loop, we check the first item in "new_list" to know if it's less than or equal to first item in "nums2".
If so, we remove the first item in "new_list" and append it to "nums1"
If not, we remove the first item in "nums2" and append it to "nums1"
the loop will continue running until one of the list becomes empty.
4. After the loop breaks, we check which of the list is not empty and add the remaining value into "nums1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment