【问题标题】:What will be the time complexity of the while loops whose iteration is not predictable?迭代不可预测的 while 循环的时间复杂度是多少?
【发布时间】:2021-04-07 12:49:44
【问题描述】:

我编写了这个算法,其中 while 循环可以根据输入数组从 N 变为 0,但我们也不能给出 O(N*N),因为如果 while 循环执行一次 N 次,那么对于x 的下一次迭代将是 0,因为我们正在从字典中删除它,结果循环将在第一次迭代中中断。那么这个算法在最坏情况下的时间复杂度是多少。 如果您需要了解算法,这就是问题所在。[https://www.youtube.com/watch?v=XitBQzqC1O0]

x=[5,4,4,3,3,2]
destroyedBaloons={}
count=0
for i in x:
    if(destroyedBaloons.get(i)):
        destroyedBaloons[i]+=1
    else:
        destroyedBaloons[i]=1
for i in x:
    if(not(destroyedBaloons.get(i))):
        continue
    height =i
    while(height>0):
        if(destroyedBaloons.get(height)):
            destroyedBaloons[height]-=1
            height-=1
        else:
            break
    count+=1    
print(count)```




 

【问题讨论】:

    标签: python time-complexity space-complexity balloon


    【解决方案1】:

    最糟糕的情况是气球按非递减顺序排列,因此每个气球都需要一个箭头。第一个循环将是 N 次迭代,然后是 N - 1N - 2 等。所以总迭代次数将是 ½(N² + N)O(N²)

    【讨论】:

    • 感谢 Yimin ,但是即使当您在 while 循环中看到气球时,如果我们没有找到要爆裂的气球,它也会在第一次迭代中中断,因为我们正在检查 a字典,那么我们如何将while循环视为N时间复杂度?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2013-12-08
    • 2016-12-17
    • 1970-01-01
    • 2017-09-02
    相关资源
    最近更新 更多