为了账号安全,请及时绑定邮箱和手机立即绑定

这个解的时间复杂度是 O(logn) 吗?

这个解的时间复杂度是 O(logn) 吗?

冉冉说 2021-10-10 15:34:51
我已经为一个挑战编写了以下解决方案,但我不确定它的时间复杂度:def ASCIIConversion(string):     newStr = ''    for chr in string:        if chr.isspace():             newStr = newStr + ' '        else:            newStr += str(ord(chr))    return newStr程序的复杂度 O(logn) 是不是因为 else 语句?
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

最坏情况下的时间复杂度计算如下(假设字符串最大长度为 n):


newStr = ''  # will be done once so 1 time.


for chr in string: # is iterating on the input with max length of n so n times.

    if chr.isspace(): # will be checked once it is in the loop so 1 time per each iteration.

        newStr = newStr + ' ' # also once per iteration if the if condition is satisfied

    else: # will be chehcked once per iteration

        newStr += str(ord(chr)) # if else is satisfied


return newStr # will be done 1 time.

我们将假设常数时间是 c 所以:


Time complexity = 1 + n(c*c + c*c) + 1 = 2+Cn => O(n)


查看完整回答
反对 回复 2021-10-10
?
呼如林

TA贡献1798条经验 获得超3个赞

这个解仍然是 O(n)。实际上,我不完全确定为什么 else 语句会影响这一点。您正在对字符串中的每个字符执行一次操作。

即使对于每个字符,您正在执行多个指令(比较等),您可能认为复杂性类似于 O(3n),但您当然忽略了系数。我相信您知道这一点,但是对于将来查看此问题、对 else 语句感到困惑的人来说,这可能会有所帮助。


查看完整回答
反对 回复 2021-10-10
?
四季花海

TA贡献1811条经验 获得超5个赞

不考虑 if-else 条件,循环遍历字符串的每个字符,因此时间复杂度为 O(n)。


查看完整回答
反对 回复 2021-10-10
  • 3 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号