[英]Time complexity for a sorted container
我正在使用 Python 的 SortedDict 容器来解决问题,并且想知道获取最高密钥的时间复杂度是多少:
from sortedcontainers import SortedDict
treeMap = SortedDict()
treeMap[1] = [4]
treeMap[1].append(6)
treeMap[3] = [9]
print(treeMap.keys()[-1]) # get the highest key in the sorted dictionary, should be 3
我知道 SortedDict 中的大多数操作都是 O(log(n)),但我对 treeMap.keys()[-1] 感到特别困惑。 对于普通字典, d.keys() 在 python3 中是 O(1) .. 是 d.keys()[-1] O(1) 吗? 在 sorteddict 或 O(n) 的情况下是 log(n),因为我需要访问最后一个元素?
sortedcontainers
SortedDict
在sortedcontainers.SortedList
中维护密钥顺序。 因此,您要询问的操作实际上是SortedList.__getitem__()
。 从文档:
__getitem__(index)[source] 在排序列表中的索引处查找值。
sl.__getitem__(index) <==> sl[index]
支持切片。
运行时复杂度:O(log(n)) – 近似值。
所以是记录时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.