Last active
March 12, 2024 01:19
-
-
Save vpodk/82d37c40891ec9926438cbf67e0327c6 to your computer and use it in GitHub Desktop.
Given two sorted arrays, merge them into a new array that is also sorted.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Merge two sorted integer arrays nums1 and nums2 into nums1, sorted in non-decreasing order. | |
* The time complexity of this function is O(m + n), | |
* @param {number[]} nums1 The first sorted array containing elements to be merged. | |
* @param {number} m The number of elements in nums1 (excluding additional space for merging). | |
* @param {number[]} nums2 The second sorted array containing elements to be merged into nums1. | |
* @param {number} n The number of elements in nums2. | |
* @see https://leetcode.com/problems/merge-sorted-array/ | |
*/ | |
var merge = function(nums1, m, nums2, n) { | |
// Initialize pointers for nums1, nums2, and the merged array | |
let i = m - 1; // Pointer for the end of nums1 | |
let j = n - 1; // Pointer for the end of nums2 | |
let k = m + n - 1; // Pointer for the end of the merged array | |
// Iterate until all elements from nums2 are merged into nums1 | |
while (j >= 0) { | |
// If there are elements remaining in nums1 and nums1's element is greater than nums2's | |
if (i >= 0 && nums1[i] > nums2[j]) { | |
// Move the larger element from nums1 to the end of the merged array | |
nums1[k--] = nums1[i--]; | |
} else { | |
// Move the element from nums2 to the end of the merged array | |
nums1[k--] = nums2[j--]; | |
} | |
} | |
}; | |
function mergeArraysES6(arrayA, arrayB) { | |
let result = [...arrayA, ...arrayB]; | |
return result.sort((valueA, valueB) => valueA - valueB); | |
} | |
function mergeArrays(arrayA, arrayB) { | |
var lengthA = arrayA.length; | |
var lengthB = arrayB.length; | |
var length = lengthA + lengthB; | |
var result = []; // or new Array(length); | |
var index = 0; | |
var indexA = 0; | |
var indexB = 0; | |
while (length--) { | |
var valueA = arrayA[indexA]; | |
var valueB = arrayB[indexB]; | |
if ((valueA < valueB || indexB == lengthB) && indexA < lengthA) { | |
result[index++] = valueA; | |
indexA++; | |
} else { | |
result[index++] = valueB; | |
indexB++; | |
} | |
} | |
return result; | |
} | |
var a = [1,2,4,5,7,334,1001]; | |
var b = [-999, 0, 1, 33, 445, 1999]; | |
console.log(mergeArraysES6(a, b)); | |
console.log(mergeArrays(a, b)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment