Python 3 中 OrderedDict 的 move_to_end 操作的时间复杂度是多少?
What is a time complexity of move_to_end operation for OrderedDict in Python 3?
我找到了 source code 它似乎是 O(1),因为它基本上是链表和字典的更新。虽然我不确定。
你怎么看?谢谢!
你可以查看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
的 linked 列表中查找 link 并更新 link 的上一个和下一个指针及其邻居。
由于上述所有操作都需要常数时间,因此 OrderedDict.move_to_end()
的复杂度也是常数。
我找到了 source code 它似乎是 O(1),因为它基本上是链表和字典的更新。虽然我不确定。
你怎么看?谢谢!
你可以查看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
的 linked 列表中查找 link 并更新 link 的上一个和下一个指针及其邻居。
由于上述所有操作都需要常数时间,因此 OrderedDict.move_to_end()
的复杂度也是常数。