We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。
请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3] nums2 = [2] 则中位数是 2.0
示例 2:
nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 + 3)/2 = 2.5
The text was updated successfully, but these errors were encountered:
利用sort()排序,排序后直接取中位数
sort()
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function(nums1, nums2) { let mergeArray = [...nums1,...nums2].sort((a, b) => a - b); return medianNums(mergeArray); }; var medianNums = function(arr){ let length = arr.length if(length%2==0){ return (arr[length/2]+arr[length/2-1])/2 }else{ return arr[(length-1)/2] } }
来自官方的图
来自lucifer
/** * 二分解法 * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function(nums1, nums2) { // make sure to do binary search for shorten array if (nums1.length > nums2.length) { [nums1, nums2] = [nums2, nums1] } const m = nums1.length const n = nums2.length let low = 0 let high = m while(low <= high) { const i = low + Math.floor((high - low) / 2) const j = Math.floor((m + n + 1) / 2) - i const maxLeftA = i === 0 ? -Infinity : nums1[i-1] const minRightA = i === m ? Infinity : nums1[i] const maxLeftB = j === 0 ? -Infinity : nums2[j-1] const minRightB = j === n ? Infinity : nums2[j] if (maxLeftA <= minRightB && minRightA >= maxLeftB) { return (m + n) % 2 === 1 ? Math.max(maxLeftA, maxLeftB) : (Math.max(maxLeftA, maxLeftB) + Math.min(minRightA, minRightB)) / 2 } else if (maxLeftA > minRightB) { high = i - 1 } else { low = low + 1 } } };
Sorry, something went wrong.
新增4.寻找两个正序数组的中位数 #142
282e967
Merge pull request #143 from zzcyes/develop
9543de2
zzcyeah
zzcyes
No branches or pull requests
题目
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。
请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
示例 2:
The text was updated successfully, but these errors were encountered: