4. 寻找两个正序数组的中位数
- 题号:4
- 来源:LeetCode
- 难度:困难
- 标签:
数组分治 - 语言:TypeScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
TypeScript · O((m+n)log(m+n)) 时间 · O(m+n) 空间 · 更新于 2026-09-27
只写了合并排序的暴力解,未写 O(log) 解
typescript
/**
* @difficulty hard
* @tags 数组,分治
* @time O((m+n)log(m+n))
* @space O(m+n)
* @note 只写了合并排序的暴力解,未写 O(log) 解
* @寻找两个正序数组的中位数
* 要求时间复杂度是O(log(m+n))
*/
/**
* @达到O(log(m+n))
*/
/**
*
* @暴力解法
* 时间O((m+n)log(m+n))
*
* 没有利用"已排序"的条件
*
*/
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
let num = []
num.push(...nums1, ...nums2) // O(m+n)
num.sort((a, b) => a - b) // O((m+n)log(m+n))
if (num.length % 2 == 0) {
return (num[num.length / 2 - 1] + num[num.length / 2]) / 2
} else {
return num[Math.floor(num.length / 2)]
}
};源码:ts/leetcode/4.寻找两个正序数组的中位数.ts
在 GitHub 上查看题目所在目录:lmliheng/algorithm