簡體   English   中英

排序容器的時間復雜度

[英]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 SortedDictsortedcontainers.SortedList中維護密鑰順序。 因此,您要詢問的操作實際上是SortedList.__getitem__() 文檔

__getitem__(index)[source] 在排序列表中的索引處查找值。

sl.__getitem__(index) <==> sl[index]

支持切片。

運行時復雜度:O(log(n)) – 近似值。

所以是記錄時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM