【问题标题】:Time complexity for a sorted container排序容器的时间复杂度
【发布时间】:2021-06-02 00:10:15
【问题描述】:

我正在使用 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),因为我需要访问最后一个元素?

【问题讨论】:

    标签: python time complexity-theory


    【解决方案1】:

    sortedcontainersSortedDictsortedcontainers.SortedList 的内部维护密钥顺序。所以你问的操作真的是SortedList.__getitem__()。来自the docs

    __getitem__(索引)[来源] 在排序列表中的索引处查找值。

    sl.__getitem__(index) sl[index]

    支持切片。

    运行时复杂度:O(log(n)) – 近似值。

    现在是记录时间。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2013-11-18
    • 2015-01-05
    • 2013-03-14
    • 2019-10-19
    相关资源
    最近更新 更多