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

2024-10-03 17:15:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

def ASCIIConversion(string): 
    newStr = ''

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

    return newStr

程序的复杂性O(logn)是因为else语句吗?你知道吗


Tags: inforstringifdef时间解决方案else
3条回答

不管if-else条件如何,循环遍历字符串的每个字符,因此时间复杂度为O(n)。你知道吗

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

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

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

相关问题 更多 >