Python求兩個有序陣列的中位數的幾種方法

2022-04-10 14:49:31 字數 2876 閱讀 9538

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]):

i += 1

else:

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)

def median_4(a, b):

# 思路四:二分法, i = 0 ~ m, j = (m + n + 1) / 2 - i, 需保證j>=0, 即n>=m

# 時間複雜度: o(log(min(m,n)))

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太大了

i_max = i - 1

elif i < m and a[i] < b[j - 1]:

# i太小了

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

求兩個有序陣列的中值

設陣列a的長度為m,陣列b的長度為n,兩個陣列都都是遞增有序的。求這兩個陣列的中值 如下 include int find median int a,int b,int m,int n,int s,int t b為空 if 0 n a p 太小了,從陣列a中找乙個更大的數嘗試 if c p 1 n ...

合併兩個有序陣列python

給定兩個有序整數陣列 nums1 和 nums2,將 nums2 合併到 nums1 中,使得 num1 成為乙個有序陣列。說明 示例 輸入 nums1 1,2,3,0,0,0 m 3 nums2 2,5,6 n 3 輸出 1,2,2,3,5,6 coding utf 8 author xinxin...

python 合併兩個有序陣列

給定兩個有序整數陣列 nums1 和 nums2,將 nums2 合併到 nums1 中,使得 num1 成為乙個有序陣列。說明 示例 輸入 nums1 1,2,3,0,0,0 m 3 nums2 2,5,6 n 3輸出 1,2,2,3,5,6 思路1.簡單粗暴,先合併再排序。嗯。這樣寫有點耍牛氓。...