美文网首页
4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

作者: jluemmmm | 来源:发表于2020-08-30 19:22 被阅读0次

    两个有序数组的中位数,相当于寻找两个数组第k大的值,利用二分法进行查找,确定之后改变k的值与起始索引。

    合并两个有序数组类似解法

    • Runtime: 120 ms, faster than 96.49% O(log(m+n))
    • Memory Usage: 41.6 MB, less than 86.12% O(1)
    var findMedianSortedArrays = function(nums1, nums2) {
        let len1 = nums1.length
        let len2 = nums2.length
        let len = len1 + len2
        if(len % 2 === 1) {
            return findKthDouble(nums1, nums2, (len + 1 ) / 2)
        } else {
            return (findKthDouble(nums1, nums2, len / 2) + findKthDouble(nums1, nums2, len / 2 + 1)) / 2
        }
    };
    
    var findKthDouble = function(nums1, nums2, k){
        let len1 = nums1.length
        let len2 = nums2.length
        let index1 = 0
        let index2 = 0
       
        while (true) {
            if (index1 === len1) {
                return nums2[index2 + k - 1]
            }
            if (index2 === len2) {
                return nums1[index1 + k - 1]
            }
            if(k === 1) {
                return Math.min(nums1[index1], nums2[index2])
            }
            let half = Math.floor(k / 2)
            let newIndex1 = Math.min(index1 + half, len1) - 1
            let newIndex2 = Math.min(index2 + half, len2) - 1
            let flag1 = nums1[newIndex1]
            let flag2 = nums2[newIndex2]
            if(flag1 <= flag2) {
                k -= (newIndex1 - index1 + 1)
                index1 = newIndex1 + 1
            } else if (flag1 > flag2) {
                k -= (newIndex2 - index2 + 1)
                index2 = newIndex2 + 1
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:4. Median of Two Sorted Arrays

          本文链接:https://www.haomeiwen.com/subject/nsbesktx.html