Skip to content

Instantly share code, notes, and snippets.

@poberwong
Last active January 7, 2021 11:39
Show Gist options
  • Save poberwong/426f243a8125b041644458a29a479bb9 to your computer and use it in GitHub Desktop.
Save poberwong/426f243a8125b041644458a29a479bb9 to your computer and use it in GitHub Desktop.
/*
* 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])
@poberwong
Copy link
Author

poberwong commented Aug 9, 2017

@lansana yeah,you're right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment