python - 这个 Big-O 表示法对于这个简单排序函数 (Python) 是否正确?
问题描述
假设我们有以下函数:
def sort_list(list_of_strings):
"""Take a list of strings, sort the letters in each string,
and then sort the full list. The list is modified in place."""
for i in range(len(list_of_strings)):
list_of_strings[i] = ''.join(sorted(list_of_strings[i]))
list_of_strings.sort()
O(n)
因为函数运行所需的时间长度取决于 的长度,所以说它具有大 O 表示法是否正确list_of_strings
?
解决方案
对大小为 N 的列表进行排序需要 O(N * log(N)) 时间(通常,这取决于确切的输入和使用的算法,但 Python 的内置排序函数不会比这更糟)。
在循环中做某事会使运行时间成倍增加,而按顺序做事意味着将运行时间加在一起。
这意味着,给定N = len(list_of_strings)
和M = max(len(string) for string in list_of_strings)
,循环的运行时间是 ,后面N * O(M * log(M)) = O(N * M * log(M))
的位是O(N * log(N))
,这意味着运行时间sort_list
是O(N * M * log(M) + N * log(N))
。
推荐阅读
- python - 尝试使用函数添加数字
- java - spring-boot-devtools 自动重启不起作用
- reactjs - 哪个主机用于响应应用程序(Google vs aws 或其他)?
- node.js - 有没有办法将类别路径解析为 Express 中的路由路径
- sql - BIDS 2005 组表达和排序
- r - 如何为每个站点提取多年来持续存在的物种、丢弃的物种或添加的物种的名称
- java - 如何将 PGProperty 与 HikariDataSource 一起使用?
- flutter - Flutter:如何将 Riverpod 与 SharedPreference 和 List 一起使用
多页变量? - php - 如何在 localhost 上运行 ioncube 编码的 laravel 项目
- download - Artifactory Nuget 存储库是否可以“直接下载云存储”?