Skip to content
New issue

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

4.寻找两个正序数组的中位数 #142

Open
zzcyes opened this issue Aug 27, 2020 · 1 comment
Open

4.寻找两个正序数组的中位数 #142

zzcyes opened this issue Aug 27, 2020 · 1 comment
Assignees
Labels
Level: ⭐⭐⭐ Hard⭐⭐⭐ Sort Sort

Comments

@zzcyes
Copy link
Owner

zzcyes commented Aug 27, 2020

Title Describe
题目 4.寻找两个正序数组的中位数
难度 ⭐⭐⭐

题目

给定两个大小为 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
@zzcyes
Copy link
Owner Author

zzcyes commented Aug 27, 2020

题解

方法一: 函数

利用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]
    }
}

方法二: 二分查找

来自官方的图

sort-005.png

来自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
    }
  }
};

zzcyes pushed a commit that referenced this issue Aug 27, 2020
新增4.寻找两个正序数组的中位数 #142
@zzcyes zzcyes added Sort Sort Level: ⭐⭐⭐ Hard⭐⭐⭐ labels Aug 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Level: ⭐⭐⭐ Hard⭐⭐⭐ Sort Sort
Projects
None yet
Development

No branches or pull requests

2 participants