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

标签 python algorithm python-3.x time-complexity

我正在尝试计算以下代码的时间复杂度。 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/

相关文章:

linq - 实现 OrderBy/ThenBy 的聪明方法是什么?

algorithm - 更有效地旋转 64 个 CCSprite?

algorithm - 跨组选择并集的下限

python - 如何在 python 3 中运行 shellcode?

python - 如果字符串与列表中的字符串匹配,如何从句子中删除字符串

python - 需要迭代行以检查条件并在满足条件时从不同列检索值

python - Django 中的 TypedChoiceField 或 ChoiceField

python - 使用 python redisearch 客户端按标签过滤搜索

python - 带有 VS2010 的 Django 在运行时给我 "ImportError: No module named django.core.management"

python - importlib.import_module 在 python3.5 中有奇怪的行为