我正在用 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
我想弄清楚用这种方法比较元素的时间复杂度。
假设:
对于这些列表,在使用指针遍历它们时,我的时间复杂度为 O(A+B),但是比较元素会如何影响此函数的时间复杂度(特别是最坏情况的时间复杂度)?
编辑:2021 年 3 月 12 日 16:30 - 改写问题
答案 0 :(得分:0)
两个元素之间的比较是恒定时间,因此这不会影响您整个算法的复杂性,您已将其修正为 O(A+B)。