【问题标题】:Time complexity of nested for loop with multiple if statements具有多个 if 语句的嵌套 for 循环的时间复杂度
【发布时间】:2022-01-03 12:19:42
【问题描述】:

在这种情况下,理想的时间复杂度是多少?

For i in list1:

   If i in list2:

      If i not in list3:

         i.append(list)

提前致谢

【问题讨论】:

    标签: time-complexity dsa


    【解决方案1】:

    时间复杂度取决于您的数据结构 list1-3 及其内容的实现。假设您有一个列表,您需要完全遍历才能执行 x in list 语句:

    For i in list1: // O(n) where n is the length of list1
        If i in list2: // O(n*m) where m is the length of list2
            If i not in list3 // O(n*m*o) where o is the length of list3
    

    任何i in list2 为真的最坏情况将导致O(n*m*o) 独立,如果我在list3 上,因为您必须以任何方式检查完整的list3 并且附加的依赖If 是常量。

    任何i in list2 为false 的最佳情况将导致O(n*m),因为您不必执行list3 迭代的任何代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多