算法复杂度:if/else在for循环下 [英] Algorithm complexity: if/else under for loop

查看:64
本文介绍了算法复杂度:if/else在for循环下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在以下情况下(for循环下的if/else语句),复杂度是O(n)还是O(n ^ 2):

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.

谢谢!

推荐答案

它将是

O(n)如果做某事"和做某事"是O(1)

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

O(n ^ 2)如果做某事"和做某事"是O(n)

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

基本上,for循环的复杂性取决于it组件和no的复杂性.循环.

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

这篇关于算法复杂度:if/else在for循环下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆