python - 迭代不可预测的 while 循环的时间复杂度是多少?
问题描述
我写了这个算法,其中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)```
解决方案
最糟糕的情况是气球按非递减顺序排列,因此每个气球都需要一个箭头。第一个循环将是N次迭代,然后是N - 1、N - 2等,因此总迭代次数将是½(N² + N)或O(N²)。
推荐阅读
- javascript - 在单元测试松散类型的语言中,是否应该检查方法的返回类型?
- python - 我可以在会话之外或在创建会话之间有挂钩/回调吗?
- ios - 在 iOS 10 上的 PassKitCore 中验证 pkpass(存折通行证)的方法/类
- html - Bootstrap:扩展导航栏切换到菜单图标,使点击时覆盖导航栏
- html - 我在将事件绑定到 AJAX 填充列表项时遇到问题。我希望能够打开一个表单并根据列表项值填写其字段
- curve-fitting - 如果回归线垂直于 x 轴,如何使用最小二乘法计算方差
- visual-studio-code - VSCode C++ Intellisense 不能在远程机器上工作
- python - 在 pandas DataFrame 子集上迭代拟合回归线 - 矢量化解决方案?
- aws-glue - AWS Glue 是否提供有关 ETL 作业执行的 SLA?
- php - PHP脚本花费太多时间