Median of Two Sorted Arrays LeetCode solution in JavaScript

1
var findMedianSortedArrays = function (nums1, nums2) {
2
if (nums1.length > nums2.length) {
3
[nums1, nums2] = [nums2, nums1];
4
}
5

6
const m = nums1.length;
7
const n = nums2.length;
8
let low = 0,
9
high = m;
10

11
while (low <= high) {
12
const partitionX = Math.floor((low + high) / 2);
13
const partitionY = Math.floor((m + n + 1) / 2) - partitionX;
14

15
const maxX =
16
partitionX === 0 ? Number.MIN_SAFE_INTEGER : nums1[partitionX - 1];
17
const maxY =
18
partitionY === 0 ? Number.MIN_SAFE_INTEGER : nums2[partitionY - 1];
19

20
const minX = partitionX === m ? Number.MAX_SAFE_INTEGER : nums1[partitionX];
21
const minY = partitionY === n ? Number.MAX_SAFE_INTEGER : nums2[partitionY];
22

23
if (maxX <= minY && maxY <= minX) {
24
if ((m + n) % 2 === 0) {
25
return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
26
} else {
27
return Math.max(maxX, maxY);
28
}
29
} else if (maxX > minY) {
30
high = partitionX - 1;
31
} else {
32
low = partitionX + 1;
33
}
34
}
35

36
throw new Error("Input arrays are not sorted.");
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0