LearningRecord
LearningRecord copied to clipboard
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log(m+n))
示例 1:
nums1 = [1, 3] nums2 = [2] 中位数是 2.0
示例 2:
nums1 = [1, 2] nums2 = [3, 4] 中位数是(2 + 3) / 2 = 2.5
function getSolution(a, b) {
const [al, bl] = [a.length, b.length]
const maxIndex = (al + bl) / 2
if (!maxIndex) {
throw Error('empty!')
}
const res = []
let cursor = 0
while(a.length && b.length && cursor++ <= maxIndex) {
res.unshift(a[0] < b[0] ? a.shift() : b.shift())
}
while (a.length && cursor++ <= maxIndex) {
res.unshift(a.shift())
}
while (b.length && cursor++ <= maxIndex) {
res.unshift(b.shift())
}
return maxIndex !== ~~maxIndex ? res[0] : (res[0] + res[1]) / 2
}