Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ffb787f

Browse files
committedJan 21, 2023
Add solution #4
1 parent 4887057 commit ffb787f

File tree

1 file changed

+1
-25
lines changed

1 file changed

+1
-25
lines changed
 

‎solutions/0004-median-of-two-sorted-arrays.js

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,6 @@
1111
* You may assume nums1 and nums2 cannot be both empty.
1212
*/
1313

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:
3914
/**
4015
* @param {number[]} nums1
4116
* @param {number[]} nums2
@@ -44,6 +19,7 @@ var findMedianSortedArrays = function(nums1, nums2) {
4419
var findMedianSortedArrays = function(nums1, nums2) {
4520
const sorted = [...nums1, ...nums2].sort((a, b) => a - b);
4621
const index = Math.floor((sorted.length - 1) / 2);
22+
4723
return sorted.length % 2 === 0
4824
? (sorted[index] + sorted[index + 1]) / 2
4925
: sorted[index];

0 commit comments

Comments
 (0)
Please sign in to comment.