比较两个列表中元素的复杂性

时间:2021-03-12 15:17:07

标签: python algorithm time-complexity complexity-theory

我正在用 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 - 改写问题

1 个答案:

答案 0 :(得分:0)

两个元素之间的比较是恒定时间,因此这不会影响您整个算法的复杂性,您已将其修正为 O(A+B)。

相关问题