简体   繁体   English

迭代空列表的时间复杂度

[英]Time complexity iterating empty list

In the following code what would be the best case complexity?在下面的代码中,最好的情况复杂度是多少? Is the best case input an empty list which means the loop doesn't iterate and therefore O(1)?最好的情况是输入一个空列表,这意味着循环不会迭代,因此 O(1)? Or should you consider it as a loop that always iterates n times and therefore O(n), regardless of input?或者你应该将它视为一个循环,无论输入如何,它总是迭代 n 次,因此是 O(n)?

def f(L, x): 
    n = len(L) 
    c = 0 
    for i in range(n): 
        if L[i] == x: 
            c = c + 1 
    return c 

It would always be O(n), since no matter the input the loop will always iterate n times.它总是 O(n),因为无论输入如何,循环都会迭代 n 次。 N being equal to 1 would not make the complexity ever equal O(1), O(1) is reserved only for atomic operations that no matter what will be O(1). N 等于 1 不会使复杂度永远等于 O(1),O(1) 仅保留用于原子操作,无论 O(1) 是什么。

Basically O(N) refers to the fact that this code snippet's time depends on N in a linear way.基本上 O(N) 指的是这个代码片段的时间以线性方式依赖于 N。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM