leetcode 004 Median of Two Sorted Arrays

本文详细解析了LeetCode上的第4题“两个有序数组的中位数”。通过递归方式寻找第k个元素,利用二分查找思想,有效地将搜索范围逐步缩小,最终找到中位数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 004 Median of Two Sorted Arrays

先找第k个,再把第k个设为中间值就是答案。
类似二分查找的思想,k大于一半时小于一半时分别对应与不同的舍弃搜索范围的情况。
例如当k大于一半时,比较两个数组的中间元素,舍弃较小元素所属的数组的前一半,对剩余进行同样的查找(注意更新k,要减去该数组长度的一半)。这样每次缩小范围为原来的四分之三。

# 2018/03/09
# exercise on leetcode

class Solution():
    def findMedianSortedArrays(self, A, B):
        a, b = len(A), len(B)
        if (a + b) & 1 == 0:
            return (self.findKthOfTwoSortedArrays(A, B, int((a + b)/2)) +
                self.findKthOfTwoSortedArrays(A, B, int((a + b)/2 - 1)))/2.0
        else:
            return self.findKthOfTwoSortedArrays(A, B, int((a + b)/2))

    def findKthOfTwoSortedArrays(self, A, B, k):

        if not A:
            return B[k]
        if not B:
            return A[k]
        if k == 0:
            return min(A[0], B[0])

        a, b = len(A), len(B)
        if A[int(a/2)] >= B[int(b/2)]:
            if k > int(a/2) + int(b/2):
                return self.findKthOfTwoSortedArrays(A[:], B[int(b/2) + 1:], k - int(b/2) - 1)
            else:
                return self.findKthOfTwoSortedArrays(A[:int(a/2)], B[:], k)
        else:
            return self.findKthOfTwoSortedArrays(B, A, k)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值