Last active
July 2, 2018 06:25
-
-
Save RameshRM/b869717d935b60eb788271cb23dd7a66 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
function findMedian(input1, input2) { | |
let resultList = sortLists(input1 || [], input2 || []); | |
if (resultList.length > 0) { | |
let medianIdx = Math.floor(resultList.length / 2); | |
if (resultList.length % 2 === 0) { | |
return (resultList[medianIdx - 1] + resultList[medianIdx]) / 2; | |
} else { | |
return resultList[medianIdx]; | |
} | |
} | |
} | |
function sortLists(input1, input2) { | |
let result = []; | |
let jIdx = 0; | |
for (var i = 0; i < input1.length; i++) { | |
for (var j = jIdx; j < input2.length && input1[i] > input2[j]; j++) { | |
result.push(input2[j]); | |
jIdx = j + 1; | |
} | |
result.push(input1[i]); | |
} | |
if (jIdx === 0) { | |
result = result.concat(input2); | |
} | |
return result; | |
} | |
console.log(findMedian([1, 2], [3, 4]) === 2.5); | |
console.log(lib.findMedian([1, 5, 9, 10, 15, 20], [2, 3, 8, 13])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment