LeetCode: 88. Merge Sorted Array Javascript Solution

preview_player
Показать описание
In this video I go over how to optimally solve problem 88 on LeetCode using Javascript and all the mishaps and flawed approaches along the way that led me to a personal epiphany about how to approach problem solving.

Initially I thought of creating a temporary array, iterating over both nums1 and nums2 respectively and pushing smaller value but this approach as well as others I've tried turned out to be flawed.

Instead I used a two pointer technique to solve the problem, I initialized three pointers to keep track of values in both nums1 and nums2 and a pointer to keep track of where to insert elements

Steps:

- Initialize three pointers, p1, p2, and p, which start at the last index of nums1(m), nums2, and nums1(m+n), respectively.
- Create a while loop that continues as long as both p1 and p2 are greater than or equal to zero.
- Within the while loop, compare the values at nums1[p1] and nums2[p2]. If nums2[p2] is larger, the value is copied to nums1[p] and p2 is decremented. If nums1[p1] is larger, the value is copied to nums1[p] and p1 is decremented. After each copy, p is decremented.
- After the first while loop terminates, if p2 is still greater than or equal to zero, another while loop is executed to copy the remaining values from nums2 to nums1.
- After both while loops have completed, the merged and sorted array will be stored in nums1.

Solution on Github:

Detailed thought process:

Medium Article:
Рекомендации по теме
welcome to shbcf.ru