【发布时间】:2019-07-15 10:54:03
【问题描述】:
我找到了source code,它似乎是 O(1),因为它基本上是一个链表和一个字典的更新。虽然我不确定。
你怎么看?谢谢!
【问题讨论】:
标签: python python-3.x time-complexity ordereddictionary
我找到了source code,它似乎是 O(1),因为它基本上是一个链表和一个字典的更新。虽然我不确定。
你怎么看?谢谢!
【问题讨论】:
标签: python python-3.x time-complexity ordereddictionary
可以查看OrderedDict.move_to_end()的纯Python实现,相当于C实现:
def move_to_end(self, key, last=True):
'''Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
'''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
soft_link = link_next.prev
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
root.prev = soft_link
last.next = link
else:
first = root.next
link.prev = root
link.next = first
first.prev = soft_link
root.next = link
基本上,此方法在字典self.__map 的链表中查找链接,并更新链接及其邻居的前一个和下一个指针。
由于上述所有操作都需要恒定的时间,OrderedDict.move_to_end() 的复杂度也是恒定的。
【讨论】: