Lintcode 65. Median of two Sorted Arrays (Hard) (Python)

本文介绍了一个算法挑战,即找到两个已排序数组的中位数,通过实现一个高效的解决方案,整体运行时间复杂度达到O(log(m+n))。示例展示了如何处理不同大小的数组,包括奇数和偶数长度的情况。

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

Median of two Sorted Arrays

Description:

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.

Example
Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

Challenge
The overall run time complexity should be O(log (m+n)).

Code:

class Solution:
    """
    @param: A: An integer array
    @param: B: An integer array
    @return: a double whose format is *.5 or *.0
    """
    def findMedianSortedArrays(self, A, B):
        # write your code here
        le = len(A)+len(B)
        if le%2==0:
            print('even')
            print('left', self.findK(A,B,int(le/2)))
            print('right', self.findK(A,B,int(le/2)+1))
            return (self.findK(A,B,int(le/2))+self.findK(A,B,int(le/2)+1))/2
        else:
            return self.findK(A,B,int(le/2)+1)
        
    def findK(self, A, B, k):
        la, lb = len(A), len(B)
        halfk = int(k/2)
        print('halfk', k, halfk)
        if la<lb:
            return self.findK(B, A, k)
        if lb == 0:
            return A[k-1]
        if k==1:
            return min(A[0], B[0])
        ib = min(lb, halfk) if halfk!=0 else 1
        ia = k-ib if k-ib!=0 else 1
        print('ia,ib',ia,ib)
        if B[ib-1]==A[ia-1]:
            return B[ib-1]
        if B[ib-1]<A[ia-1]:
            
            if lb==ib:
                return A[ia-1]
            return self.findK(A[:ia], B[ib:], ia)
        if B[ib-1]>A[ia-1]:
            if la==ia:
                return B[ib-1]
            return self.findK(A[ia:], B[:ib], ib)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值