Skip to content

Commit 5a98d83

Browse files
committed
Add solution #4
1 parent aebee3a commit 5a98d83

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
|#|Title|Difficulty|
88
|:---|:---|:---|
9+
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
910
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
1011
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
1112
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 4. Median of Two Sorted Arrays
3+
* https://leetcode.com/problems/median-of-two-sorted-arrays/
4+
* Difficulty: Hard
5+
*
6+
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
7+
*
8+
* Find the median of the two sorted arrays.
9+
* The overall run time complexity should be O(log (m+n)).
10+
*
11+
* You may assume nums1 and nums2 cannot be both empty.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums1
16+
* @param {number[]} nums2
17+
* @return {number}
18+
*/
19+
var findMedianSortedArrays = function(nums1, nums2) {
20+
const total = nums1.length + nums2.length;
21+
const limit = Math.floor(total / 2) + 1;
22+
let i = 0, j = 0, prev, last
23+
24+
while(i + j < limit) {
25+
if (last !== undefined) {
26+
prev = last;
27+
}
28+
if (nums1[i] < nums2[j] || j === nums2.length) {
29+
last = nums1[i++];
30+
} else {
31+
last = nums2[j++];
32+
}
33+
}
34+
35+
return total % 2 === 0 ? (prev + last) / 2 : last;
36+
};
37+
38+
// shorter/readable alternative with higher time complexity:
39+
/**
40+
* @param {number[]} nums1
41+
* @param {number[]} nums2
42+
* @return {number}
43+
*/
44+
var findMedianSortedArrays = function(nums1, nums2) {
45+
const sorted = [...nums1, ...nums2].sort((a, b) => a - b);
46+
const index = Math.floor((sorted.length - 1) / 2);
47+
return sorted.length % 2 === 0
48+
? (sorted[index] + sorted[index + 1]) / 2
49+
: sorted[index];
50+
};

0 commit comments

Comments
 (0)