gpt4 book ai didi

python - 计算这段具体代码的时间复杂度

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:25 25 4
gpt4 key购买 nike

我正在尝试计算以下代码的时间复杂度。 lst_of_lsts 包含长度至多为 nm 列表。

这就是我的想法:所有运行在 O(m*n) 中,最小值 = O(m*n),remove = O(m *n).

总体 O(m*n)*O(m*n) = O(m^2*n^2)

我说得对吗?

 def multi_merge_v1(lst_of_lsts): 
all = [e for lst in lst_of_lsts for e in lst]
merged = []
while all != []:
minimum = min(all)
merged += [minimum]
all.remove(minimum)
return merged

最佳答案

def multi_merge_v1(lst_of_lsts): # M lists of N
all = [e for lst in lst_of_lsts for e in lst]
# this is messy. Enumerate all N*M list items --> O(nm)

merged = [] # O(1)
while all != []: # n*m items initially, decreases in size by 1 each iteration.
minimum = min(all) # O(|all|).
# |all| diminishes linearly from (nm) items, so this is O(nm).
# can re-use work here. Should use a sorted data structure or heap

merged += [minimum] # O(1) amortized due to table doubling
all.remove(minimum) # O(|all|)
return merged # O(1)

整体复杂度似乎为 O(nm + nm*nm + 1) = O(n^2m^2+1)。哎呀。

关于python - 计算这段具体代码的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com