Given two sorted arrays nums1 and nums2, return the median of the two arrays combined. The overall run time should be O(log(m + n)).
Cut both arrays so the left halves together hold half the elements. Binary-search the cut in the shorter array until every left value is ≤ every right value; the median sits at the cut.
1function findMedianSortedArrays(a: number[], b: number[]): number {2if (a.length > b.length) [a, b] = [b, a];3const m = a.length, n = b.length, half = (m + n + 1) >> 1;4let lo = 0, hi = m;5while (lo <= hi) {6const i = (lo + hi) >> 1, j = half - i;7const aL = i ? a[i - 1] : -Infinity, aR = i < m ? a[i] : Infinity;8const bL = j ? b[j - 1] : -Infinity, bR = j < n ? b[j] : Infinity;9if (aL <= bR && bL <= aR)10return (m + n) % 2 ? Math.max(aL, bL) : (Math.max(aL, bL) + Math.min(aR, bR)) / 2;11if (aL > bR) hi = i - 1;12else lo = i + 1;13}14return 0;15}
Binary search the cut in a over [0, 5]. Left halves must hold 6 values.
Space: play/pause · ←/→: step