计算此特定代码的时间复杂度

时间:2014-04-06 14:51:40

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

我试图找出以下代码的时间复杂度。 lst_of_lsts包含m个列表,其长度最多为n

我认为:所有内容都在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 

1 个答案:

答案 0 :(得分:1)

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)。让人惊讶。