求两个有序数组的中位数的几种方法
思路一:
def median_1(A, B):
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):
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 = 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)
思路四:
def median_4(A, B):
m, n = len(A), len(B)
if m > n:
m, n, A, B = n, m, B, A
if n == 0:
raise ValueError
i_min = 0
i_max = m
half = (m + n + 1) // 2
while i_min <= i_max:
i = (i_min + i_max) // 2
j = half - i
if i > 0 and A[i - 1] > B[j]:
i_max = i - 1
elif i < m and A[i] < B[j - 1]:
i_min = i + 1
else:
if i == 0:
max_of_left = B[half - 1]
elif j == 0:
max_of_left = A[half - 1]
else:
max_of_left = max(A[i - 1], B[j - 1])
if (m + n) % 2 == 1:
return max_of_left
if i == m:
min_of_right = B[j]
elif j == n:
min_of_right = A[i]
else:
min_of_right = min(A[i], B[j])
return (max_of_left + min_of_right) / 2
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步