【问题标题】:Is the time complexity of this solution O(logn)?这个解决方案的时间复杂度是 O(logn) 吗?
【发布时间】:2019-01-13 13:21:56
【问题描述】:

我为一个挑战编写了以下解决方案,但我不确定它的时间复杂度:

def ASCIIConversion(string): 
    newStr = ''

    for chr in string:
        if chr.isspace(): 
            newStr = newStr + ' '
        else:
            newStr += str(ord(chr))

    return newStr

程序的复杂度,O(logn),是因为 else 语句吗?

【问题讨论】:

  • 你遍历字符串数组,应该是O(n)。循环内的所有语句都是常数时间,包括 if 和 else。
  • 其实我现在正在学习大O表示法,看来我有一些误解。谢谢!

标签: python time-complexity big-o


【解决方案1】:

最坏情况下的时间复杂度计算如下(假设字符串最大长度为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)

【讨论】:

  • @TrebuchetMS 谢谢。完成:)
【解决方案2】:

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

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

【讨论】:

  • 其实我现在正在学习大O表示法,看来我有一些误解。感谢您的详尽回答!
  • @cpit 没问题!作为一般的经验法则,您可以只计算 for 和 while 循环的数量并从那里计算出来。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多