add: 寻找两个正序数组的中位数

This commit is contained in:
yi-ge 2020-05-24 19:16:28 +08:00
parent c371738884
commit 581a96e795
3 changed files with 64 additions and 0 deletions

View File

@ -390,6 +390,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 507. 完美数 <https://leetcode-cn.com/problems/perfect-number/>
- LintCode 1199. 完美的数 <https://www.lintcode.com/problem/perfect-number/description>
- [寻找两个正序数组的中位数](src/math/median-of-two-sorted-arrays.js)
- LeetCode 4. 寻找两个正序数组的中位数 <https://leetcode-cn.com/problems/median-of-two-sorted-arrays/>
- LintCode 65. 两个排序数组的中位数 <https://www.lintcode.com/problem/median-of-two-sorted-arrays/description>
## 堆
- [超级丑数](src/stack/super-ugly-number.js)【未完成】

View File

@ -0,0 +1,52 @@
// 中位数:将一个集合划分为两个长度相等的子集,其中一个子集中的元素总是大于另一个子集中的元素。
// 参考https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-s-114/
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
export const findMedianSortedArrays = function (nums1, nums2) {
if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1)
const m = nums1.length; const n = nums2.length
let left = 0; let right = m
let median1 = 0; let median2 = 0
while (left <= right) {
const i = (left + right) >> 1
const j = ((m + n + 1) >> 1) - i
const numsIm1 = (i === 0 ? Number.MIN_SAFE_INTEGER : nums1[i - 1]) // nums1[i-1]
const numsI = (i === m ? Number.MAX_SAFE_INTEGER : nums1[i]) // nums1[i]
const numsJm1 = (j === 0 ? Number.MIN_SAFE_INTEGER : nums2[j - 1]) // nums2[j-1]
const numsJ = (j === n ? Number.MAX_SAFE_INTEGER : nums2[j]) // nums2[j]
if (numsIm1 <= numsJ) {
median1 = Math.max(numsIm1, numsJm1)
median2 = Math.min(numsI, numsJ)
left = i + 1
} else {
right = i - 1
}
}
return (m + n) % 2 === 0 ? (median1 + median2) / 2.0 : median1
}
// 常规解法,不满足复杂度
// /**
// * @param {number[]} nums1
// * @param {number[]} nums2
// * @return {number}
// */
// var findMedianSortedArrays = function(nums1, nums2) {
// const newArr = nums1.concat(nums2).sort((a, b) => a - b)
// const length = newArr.length
// if (length % 2 === 0) {
// const half = length / 2
// return (newArr[half - 1] + newArr[half]) / 2
// } else {
// return newArr[(length - 1) / 2]
// }
// };

View File

@ -0,0 +1,7 @@
import { findMedianSortedArrays } from '../../src/math/median-of-two-sorted-arrays'
test('寻找两个正序数组的中位数', () => {
expect(findMedianSortedArrays([], [1])).toBe(1.0)
expect(findMedianSortedArrays([1, 3], [2])).toBe(2.0)
expect(findMedianSortedArrays([1, 2], [3, 4])).toBe(2.5)
})