Median of Two Sorted Arrays
Descriptions
original description
Solutions
First Idea
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function (nums1, nums2) {
const len = nums1.length + nums2.length;
const max = len % 2 ? (len - 1) / 2 : len / 2;
let prev = null;
let pprev = null;
let cur1 = 0;
let cur2 = 0;
for (let i = 0; i <= max; i++) {
pprev = prev;
prev =
(nums1[cur1] ?? Number.MAX_VALUE) < (nums2[cur2] ?? Number.MAX_VALUE)
? nums1[cur1++]
: nums2[cur2++];
}
return len % 2 ? prev : (pprev + prev) / 2;
};
- Time Complexity: O(n)
- Space Complexity: O(1)