guyuezhai / interviewSummary

some summary of interview
0 stars 0 forks source link

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log(m+n)) #18

Open guyuezhai opened 4 years ago

guyuezhai commented 4 years ago

示例 1:

nums1 = [1, 3] nums2 = [2]

中位数是 2.0

示例 2:

nums1 = [1, 2] nums2 = [3, 4]

中位数是(2 + 3) / 2 = 2.5

guyuezhai commented 4 years ago

第一步合并两个有序数组

第二步根据最终数组的长度是奇偶 求得中位数

let nums1 = [1,2,3,5, 9]
let nums2 = [2,4,6,8]

function mergeSort(arr1,arr2){
    let sortRes=merge(arr1,arr2)
    let len=sortRes.length
    let mid=len>>1
    let result
    if(len%2==0){
        result=(sortRes[mid]+sortRes[mid-1])/2
    }else{
        result=sortRes[mid]
    }
    return result
}
function merge(arr1,arr2){
    let result=[];
    let llen=arr1.length;
    let rlen=arr2.length;
    let i=j=0;
    while(i<llen && j<rlen){
        if(arr1[i]<arr2[j]){
            result.push(arr1[i++])
        }else{
            result.push(arr2[j++])
        }
    }
    while(i<llen){
        result.push(arr1[i++])
    }
    while(j<rlen){
        result.push(arr2[j++])
    }
    return result
}

let result = mergeSort(nums1,nums2)