给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,
中位数 (2+ 3) / 2 = 2.5
https://leetcode-cn.com/problems/median-of-two-sorted-arrays
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function (nums1, nums2) {
if (nums1.length == 0 && nums2.length == 0) {
return 0
}
if (nums2.length == 0) {
let isOdd = nums1.length % 2 == 1
if (isOdd) {
return nums1[~~(nums1.length / 2)]
} else {
return (nums1[nums1.length / 2] + nums1[nums1.length / 2 - 1]) / 2
}
}
if (nums1.length == 0) {
let isOdd = nums2.length % 2 == 1
if (isOdd) {
return nums2[~~(nums2.length / 2)]
} else {
return (nums2[nums2.length / 2] + nums2[nums2.length / 2 - 1]) / 2
}
}
let i = 0;
let j = 0;
let total = nums1.length + nums2.length
let isOdd = total % 2 == 1
let lastNum = 0
let nowNum = 0
while (true) {
if (i + j > (~~(total / 2))) {
if (isOdd) {
return nowNum
} else {
return (lastNum + nowNum) / 2
}
}
if (nums1[i] == undefined) {
lastNum = nowNum
nowNum = nums2[j]
j++
continue
}
if (nums2[j] == undefined) {
lastNum = nowNum
nowNum = nums1[i]
i++
continue
}
if (nums1[i] < nums2[j]) {
lastNum = nowNum
nowNum = nums1[i]
i++
} else {
lastNum = nowNum
nowNum = nums2[j]
j++
}
}
};