python - Python 3 的时间复杂度

标签 python python-3.x time-complexity

以下代码适用于 hackerrank 问题: (A和B默认会得到非重复且离散的数据)

n,m = map(int,input().split())
arr = list(map(int,input().split()))
A = set(map(int,input().split()))
B = set(map(int,input().split()))
count = 0
for x in arr:
    if x in A:
        count+=1
    if x in B:
        count-=1
print(count)

但下一个在 4 个测试用例中显示时间错误:

n,m = map(int,input().split())
arr = list(map(int,input().split()))
A = list(map(int,input().split()))
B = list(map(int,input().split()))
count = 0
for x in arr:
    if x in A:
        count+=1
    if x in B:
        count-=1
print(count)

列表和集合的时间复杂度如何急剧变化以及它们如何工作?

最佳答案

Python 中的

set 是使用 hash table 实现的。 .

检查集合中是否存在元素是一个O(1)(即恒定时间)操作,并且此检查的执行时间不取决于集合中有多少个元素.

list 被实现为数组,检查元素是否存在需要 O(n),其中 n 是元素数量在列表中。检查某个元素是否存在于包含 1000 个元素的列表中所需的时间是列表仅包含 100 个元素时所需时间的十倍。

关于python - Python 3 的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464891/

相关文章:

python - 使用 pandas 或 matplotlib 在 IPython 笔记本中绘制性别图表

python - 如何获取数字的最后 2 位数字(整数或小数)

python-3.x - 如何在静默安装期间更改 EXE 文件的目标目录/安装路径

python - Django REST Framework 序列化器验证错误

python - 如何提高比较列表元素的效率?

python - Pygame 没有正确处理键盘或鼠标事件

python - pyspark 导入用户定义的模块或 .py 文件

python - 无效的文件错误Python?

python - 如何加快 numpy.append 速度

algorithm - 给定 O(n) 集合,找出其中不同的集合的复杂性是多少?