Algorithm complexity: if/else under for loop

余生长醉 提交于 2021-02-07 08:00:34

问题


I am wondering if in a situation like the following (an if/else statement under a for loop) the complexity would be O(n) or O(n^2):

for character in string:
    if character==something:
        do something
    else:
        do something else.

Thank you!


回答1:


It will be

O(n) if 'do something' and 'do something else' are O(1)

O(n^2) if 'do something' and 'do something else' are O(n)

Basically the complexity of the for loop will depend on the complexity of it components and the no. of loops.




回答2:


It depends what you are doing in the else statement, but I believe it is O(n) because worst case you go through the string n times.




回答3:


Put simply, O(n) basically means the algorithm will take as much time to execute as there are elements in n. O(1) means the algorithm always takes a constant time, regardless of how many elements are in the input. O(n^2) means the algorithm takes number of items squared time (i.e. slows down more and more the bigger the input is).

In your case you're doing the same kind of thing for every item in the input once. if..else is just one normal statement you do to each item once. It does neither increase nor decrease the runtime/complexity. Your algorithm is O(n).



来源:https://stackoverflow.com/questions/31164749/algorithm-complexity-if-else-under-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!