python - 比较两个列表中元素的复杂性
问题描述
我在 Python 中编写了一个函数来查找另一个排序列表中存在的排序列表的元素并打印出结果:
# assume that both lists are sorted
def compare_sorted_lists(list1, list2):
res = []
a = 0
b = 0
while a < len(list1) and b < len(list2):
if list1[a] == list2[b]:
res.append(list1[a])
a += 1
elif list1[a] < list2[b]:
a += 1
else:
b += 1
return res
我想弄清楚用这种方法比较元素的时间复杂度。
假如说:
- list1 的长度为 A 并且 list1 元素中的最大数字/字母数是 X
- list2 的长度为 B 并且 list2 元素中的最大数字/字母数为 Y
对于这些列表,我在用指针遍历它们时具有 O(A+B) 时间复杂度,但是比较元素将如何影响此函数的时间复杂度(特别是最坏情况下的时间复杂度)?
编辑:2021 年 3 月 12 日 16:30 - 改写的问题
解决方案
两个元素之间的比较是恒定时间,因此这不会影响整个算法的复杂性,您将其更正为 O(A+B)。
推荐阅读
- assembly - mov dword ptr [eax], 5 和 mov dword [eax], 5 有什么区别?
- c# - 具有 Graph API 分页调用的持久函数?
- python - 如何从输入框中获取自定义输入以形成特定的超链接?
- python - 我正在尝试使用 Django_tables2 将应用程序部署到 Heroku 并收到“ImportError: cannot import name 'FieldDoesNotExist'”
- python - 在 Python 中将人类可读时间转换为纪元时间戳
- ruby-on-rails - 未知验证器:Ruby on Rails 上的“InValidator”
- firebase - 删除按钮颤动 Firestore
- angular - 为什么我的 Mongoose 控制器没有被调用?
- reactjs - 在我的 Redux 设置中没有调用 Reducer
- c++ - 转换为右值后,线程参数必须是可调用的