我的js算法爬坑之旅-寻找两个正序数组的中位数

187 阅读1分钟

第十七天:力扣第4题,寻找两个正序数组的中位数

地址:leetcode-cn.com/problems/me…

思路:一开始就是先组合排序再进行查中:

var findMedianSortedArrays = function(nums1, nums2) {
    let a = nums1.concat(nums2);
    a = a.sort((b,c) => b - c);
    if(a.length%2 == 0&&a.length != 1)//对奇数组和偶数组的判断
    {
       return  (a[a.length / 2 - 1] + a[a.length / 2]) / 2;
    }
    else{
        return a[(a.length-1)/2];
    }
};

好像是简单题,但是标注的是困难题,我就知道没那么简单了,题目要时间复杂度为:

O(log (m+n))

但是我的题解时间复杂度为:O(m+n)

所以肯定不是暴力解题。

使用二分查找可以使得时间复杂度符合题目:

var findMedianSortedArrays = function(nums1, nums2) {
  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
    }
  }
};