diff --git a/README.md b/README.md index 50e2dac..7a3a3fb 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 507. 完美数 - LintCode 1199. 完美的数 +- [寻找两个正序数组的中位数](src/math/median-of-two-sorted-arrays.js) + + - LeetCode 4. 寻找两个正序数组的中位数 + - LintCode 65. 两个排序数组的中位数 + ## 堆 - [超级丑数](src/stack/super-ugly-number.js)【未完成】 diff --git a/src/math/median-of-two-sorted-arrays.js b/src/math/median-of-two-sorted-arrays.js new file mode 100644 index 0000000..5e56fb1 --- /dev/null +++ b/src/math/median-of-two-sorted-arrays.js @@ -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] +// } +// }; diff --git a/test/math/median-of-two-sorted-arrays.test.js b/test/math/median-of-two-sorted-arrays.test.js new file mode 100644 index 0000000..485bfe8 --- /dev/null +++ b/test/math/median-of-two-sorted-arrays.test.js @@ -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) +})