Skip to content

Instantly share code, notes, and snippets.

@omardeleo
Created November 19, 2019 00:14
Show Gist options
  • Save omardeleo/19e695f5f8d20d2ff60ae3a47d00d926 to your computer and use it in GitHub Desktop.
Save omardeleo/19e695f5f8d20d2ff60ae3a47d00d926 to your computer and use it in GitHub Desktop.
Median of Two Sorted Arrays [Hard]
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
let count = 0;
let resArr = [];
while (nums1.length > 0 && nums2.length > 0) {
if (nums1[0] < nums2[0]) {
resArr.push(nums1.shift());
} else {
resArr.push(nums2.shift());
}
count++;
}
if (nums1.length > 0) {
count += nums1.length;
resArr = resArr.concat(nums1);
}
if (nums2.length > 0) {
count += nums2.length;
resArr = resArr.concat(nums2);
}
let indices = count % 2 === 0 ?
[count / 2, (count / 2) - 1] :
[Math.floor(count / 2), Math.floor(count / 2)]
return (resArr[indices[0]] + resArr[indices[1]]) / 2
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment