JS Likou classic 100 questions - find the median of two positive sequence arrays

4. Find the median of two ordinal arrays

Given two positively ordered (from msmall nto large) arrays of sizes  nums1and  nums2. Please find and return the median of these two ordinal arrays .

The time complexity of the algorithm should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
 Output: 2.00000
 Explanation: Combined array = [1,2,3], median 2

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
 Output: 2.50000
 Explanation: Combined array = [1,2,3,4], median (2 + 3) / 2 = 2.5

hint:

  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -106 <= nums1[i], nums2[i] <= 106

解法:没有达到预期的时间复杂度,懒人解法,将数组合并为一个有序数组,根据数组长度返回中位数

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
 var findMedianSortedArrays = function(nums1, nums2) {
    let arr = []
    let i=0, j=0, m=0
    while(i<nums1.length || j<nums2.length) {
        if(i<nums1.length && j<nums2.length) {
            arr[m] = nums1[i]<= nums2[j] ? nums1[i++] : nums2[j++]
            m++
        } else if(i<nums1.length){
            arr[m++] = nums1[i++]
        } else if(j<nums2.length){
            arr[m++] = nums2[j++]
        }
    }
    let mid = nums1.length + nums2.length
    if(mid%2 !=0) {
        let a =Math.floor(mid/2)
        return arr[a]
    } else {
        return (arr[mid/2-1]+arr[mid/2])/2
    }
};

Guess you like

Origin blog.csdn.net/qq_36384657/article/details/128173664