-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0004-MedianOfTwoSortedArrays.js
More file actions
42 lines (37 loc) · 1.18 KB
/
0004-MedianOfTwoSortedArrays.js
File metadata and controls
42 lines (37 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//-----------------------------------------------------------------------------
// Runtime: 128ms
// Memory Usage: 42.4 MB
// Link: https://leetcode.com/submissions/detail/385375252/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
const merge = ((A, B) => {
let i = 0, j = 0, C = [];
while (i < A.length && j < B.length) {
C.push(A[i] < B[j] ? A[i++] : B[j++]);
}
if (i === A.length) {
C.push(...B.slice(j));
}
if (j === B.length) {
C.push(...A.slice(i));
}
return C;
});
const nums = merge(nums1, nums2);
const n = nums.length,
m1 = Math.floor(n / 2),
m2 = Math.floor((n - 1) / 2);
return n % 2 === 1 ? nums[m1] : (nums[m1] + nums[m2]) / 2.0;
};
return {
findMedianSortedArrays: findMedianSortedArrays
};
};
module.exports = solution();