Last active
January 7, 2021 11:39
-
-
Save poberwong/426f243a8125b041644458a29a479bb9 to your computer and use it in GitHub Desktop.
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
/* | |
* time complexity = O(n) | |
*/ | |
function twoWayMerge (arr1, arr2) { | |
if (!arr1 || !arr2) { | |
return 'illegal params' | |
} | |
if (arr1.length === 0 || arr2.length === 0) { | |
return arr1.concat(arr2) | |
} | |
const result = [] | |
let i = 0, j = 0 | |
while (i < arr1.length && j < arr2.length) { | |
if(arr1[i] <= arr2[j]) { | |
result.push(arr1[i]) | |
i++ | |
} else { | |
result.push(arr2[j]) | |
j++ | |
} | |
} | |
if (i > arr1.length - 1) { | |
result.push(...arr2.slice(j)) | |
} else { | |
result.push(...arr1.slice(i)) | |
} | |
return result | |
} | |
/* | |
* time complexity = O(n*(k-1)) | |
*/ | |
function multiWaysMerge (...args) { | |
return args.reduce(twoWayMerge) | |
} | |
multiWaysMerge([0, 2, 4, 6, 8], [0, 2, 3, 5, 7], [0, 2, 4, 6, 8], [0, 2, 3, 5, 7], [0, 2, 4, 6, 8], [0, 2, 3, 5, 7]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't you check for illegal params before checking the length? If you pass undefined then an error will be thrown because a length property doesn't exist on undefined, or anything else that is not an Array-like object.