Last active
October 17, 2022 07:03
-
-
Save OlegKorn/0787bc5954f880893d6d26f79c5207a0 to your computer and use it in GitHub Desktop.
leetcode findMedianSortedArrays (https://leetcode.com/problems/median-of-two-sorted-arrays)
This file contains hidden or 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
/* | |
nums1.length == m | |
nums2.length == n | |
0 <= m <= 1000 | |
0 <= n <= 1000 | |
1 <= m + n <= 2000 | |
-10**6 <= nums1[i], nums2[i] <= 10**6 | |
*/ | |
var findMedianSortedArrays = function(nums1, nums2) { | |
// if all values of both are 0 | |
if ( | |
nums1.every(v => v === 0) && | |
nums2.every(v => v === 0) | |
) { | |
return 0 | |
} | |
nums2.push(...nums1) | |
// sort negative numbers if there are | |
nums2.sort(function(a, b) {return a-b}) | |
if (nums2.length === 1) { | |
return nums2[0] | |
} | |
else if (nums2.length % 2 === 0) { | |
var one = nums2.length / 2 - 1 | |
var two = nums2.length / 2 | |
return (nums2[one] + nums2[two]) / 2 | |
} | |
else { | |
return (nums2[Math.round(nums2.length / 2) - 1]) | |
} | |
} | |
console.log(findMedianSortedArrays([3], [-2, -1, 4, -2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment