Skip to content

Commit b61f38b

Browse files
committed
feat(leetcode): ✨ Add answer to median of two sorted arrays
1 parent 0a676fa commit b61f38b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// This is a O((m+n)/2) solution. It's a bit trickier to code the O(m+n) version.
2+
3+
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
4+
const totalLength = nums1.length + nums2.length;
5+
const halfLength = Math.floor(totalLength / 2);
6+
// Handle even and odd lengths to indexes: 20 -> 9, 10; 21 -> 10, 10
7+
const [targetIndex1, targetIndex2] = [
8+
totalLength % 2 === 0 ? halfLength - 1 : halfLength,
9+
halfLength,
10+
];
11+
12+
const arr: number[] = [];
13+
let p1 = 0,
14+
p2 = 0,
15+
n1 = 0,
16+
n2 = 0;
17+
while (p1 < nums1.length && p2 < nums2.length) {
18+
n1 = nums1[p1];
19+
n2 = nums2[p2];
20+
if (n1 <= n2) {
21+
arr.push(n1);
22+
p1 += 1;
23+
} else {
24+
arr.push(n2);
25+
p2 += 1;
26+
}
27+
28+
if (arr.length > targetIndex2) {
29+
return (arr[targetIndex1] + arr[targetIndex2]) / 2;
30+
}
31+
}
32+
33+
if (p1 === nums1.length) {
34+
arr.push(...nums2.slice(p2));
35+
} else if (p2 === nums2.length) {
36+
arr.push(...nums1.slice(p1));
37+
}
38+
return (arr[targetIndex1] + arr[targetIndex2]) / 2;
39+
}

0 commit comments

Comments
 (0)