88. Merge Sorted Array (javascript solution)
codingpineapple
Posted on February 27, 2021
Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
Solution:
Time Complexity : O(n)
Space Complexity: O(1)
// Two pointer solution
// Start by comparing the largest numbers between the two arrays and add to the end of nums1
var merge = function(nums1, m, nums2, n) {
while (n) {
if (nums1[m - 1] > nums2[n - 1]) {
nums1[m + n - 1] = nums1[--m];
} else {
nums1[m + n - 1] = nums2[--n];
}
}
return nums1;
};
💖 💪 🙅 🚩
codingpineapple
Posted on February 27, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.