Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created April 12, 2023 21:14
Show Gist options
  • Select an option

  • Save optimistiks/86521dec96ceb230ece86f869060404b to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/86521dec96ceb230ece86f869060404b to your computer and use it in GitHub Desktop.
You’re given two sorted integer arrays, nums1 and nums2, of size m and n, respectively. Your task is to return the median of the two sorted arrays. The overall run time complexity should be O(log(m+n)).
export function findMedian(nums1, nums2) {
const totalLength = nums1.length + nums2.length;
const leftHalfLength = Math.floor(totalLength / 2);
const listA = nums1.length < nums2.length ? nums1 : nums2;
const listB = nums1.length < nums2.length ? nums2 : nums1;
let l = 0;
let r = listA.length - 1;
while (true) {
let i = Math.floor((l + r) / 2);
let j = leftHalfLength - i - 2;
const leftA = listA[i] ?? -Infinity;
const rightA = listA[i + 1] ?? Infinity;
const leftB = listB[j] ?? -Infinity;
const rightB = listB[j + 1] ?? Infinity;
console.log(
`[${listA.map((value, index) => {
if (index === i) {
return `${value} |`;
}
return value;
})}]`,
`[${listB.map((value, index) => {
if (index === j) {
return `${value} |`;
}
return value;
})}]`,
{ i, j, l, r }
);
if (leftA < rightB && leftB < rightA) {
if (totalLength % 2 !== 0) {
return Math.min(rightA, rightB);
}
return (Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2;
} else if (leftA >= rightB) {
r = i - 1;
} else if (leftB >= rightA) {
l = i + 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment