Python求两个有序数组的中位数的几种方法

求两个有序数组的中位数的几种方法

思路一:

def median_1(A, B):
    # 思路一: 先组合成一个有序数列,再取中位数
    # 时间复杂度O(m+n)
    len_A = len(A)
    len_B = len(B)
    C = []
    if len_A == len_B == 0:
        raise ValueError
    i = j = 0
    for k in range(0, len_A + len_B):
        if j == len_B or (i < len_A and A[i] <= B[j]):
            C.append(A[i])
            i += 1
        else:
            C.append(B[j])
            j += 1
    half = (len_A + len_B) // 2
    if (len_A + len_B) % 2 == 0:
        return (C[half - 1] + C[half]) / 2
    else:
        return C[half]

思路二:

def median_2(A, B):
    # 思路二: 没有必要完全产生出第三个列表,我们在一开始就可以知道需要取的索引,且可以用变量记录而不新建列表
    # 时间复杂度: O((m+n)/2) => O(m+n)
    len_A = len(A)
    len_B = len(B)
    if len_A == len_B == 0:
        raise ValueError
    half = (len_A + len_B) // 2 + 1
    pre = cur = i = j = 0
    for k in range(0, half):
        if j == len_B or (i < len_A and A[i] <= B[j]):
            pre = cur
            cur = A[i]
            i += 1
        else:
            pre = cur
            cur = B[j]
            j += 1
    if (len_A + len_B) % 2 == 0:
        return (pre + cur) / 2
    else:
        return cur

思路三:

def median_3(A, B, k=None):
    # 思路三: 求中位数的问题可以看作是求第(m+n)/2小的数的问题.如果是偶数个,则是第(m+n)/2小和第(m+n)/2+1小的均值.
    # 时间复杂度: O(log(m+n))
    m, n = len(A), len(B)
    if m > n:
        n, m, A, B = m, n, B, A
    if n == 0:
        raise ValueError
    if k == None:
        k1 = (m + n + 1) // 2
        k2 = (m + n + 2) // 2
        return (median_3(A, B, k1) + median_3(A, B, k2)) / 2
    if m == 0:
        return B[k - 1]
    if k == 1:
        return A[0] if A[0] <= B[0] else B[0]
    half = k // 2
    index_A = min(m - 1, half - 1)
    index_B = min(n - 1, half - 1)
    if A[index_A] <= B[index_B]:
        return median_3(A[index_A + 1:], B, k - index_A - 1)
    else:
        return median_3(A, B[index_B + 1:], k - index_B - 1)

思路四:

posted @   怀心抱素  阅读(1861)  评论(2编辑  收藏  举报
点击右上角即可分享
微信分享提示