python - Python - 列表中 O(n^2) 跳转次数的复杂性
问题描述
如果一个列表有 3 个元素,那么 O(n^2) 意味着我们必须进行 9 次跳转来导航 3 个元素的集合吗?如果一个跳跃只是一个元素,怎么可能是 9 次跳跃?
list = [1, 2, 3]
我不明白作者的意思是我们必须进行 9 次跳跃。有人可以解释一下吗?
解决方案
下面提供的代码示例是O(n)
因为它使用 for 循环来迭代n
元素。
n = len(list) # n = the length of the list here 3.
for i in range(0, n): # This runs n = 3 times, where n is the size of the list O(n)
print(i)
现在考虑一个嵌套的 for 循环,这意味着您当前的 for 循环中的第二个循环。这是O(n^2)
由于迭代n*n
元素。
n = len(list) # n = the length of the list here 3.
for i in range(0, n): # This runs n = 3 times.
for j in range (0, n): # This runs n = 3 times for each value of the i.
print(j)
可以这样想,上面的代码段0, 1, 2
在内循环中打印的次数与外循环指定的次数一样,在这种情况下为 3。因此,最后0, 1, 2, 0, 1, 2, 0, 1, 2
将打印正好n*n
= 3*3
=9
元素。
推荐阅读
- laravel - laravel 如何首先重定向到公用文件夹?
- lxd - LXD 的 snap 包版本在哪里存储容器?
- python - Pyspark - 具有重置条件的累积和
- multithreading - 如何使用多线程高效运行拓扑排序?
- angular - 如何在地图管道 RXJS(Angular)中模拟错误?
- java - Set.visible 实际上并没有为我做任何事情,或者 thread.sleep 把我搞砸了
- powershell - 如何修复简单的纠缠单元测试
- angular - 将 ActivatedRoute queryParams 订阅拆分为多个订阅
- ruby-on-rails - 使用 SemanticLogger gem 在 Rails 控制台中显示 SQL ActiveRecord 查询
- python - 将图像发送到 Telegram 时出现“请求实体太大”错误的原因是什么?