简体   繁体   English

时间复杂度:删除双端队列的元素

[英]Time complexity: deleting element of deque

What is the time complexity of deleting an element of collections.deque ?删除collections.deque的元素的时间复杂度是多少?

Eg:例如:

deq = collections.deque([1, 2, 3])
del deq[1]

Summary概括

The time complexity is O(n) where n is the distance to the nearest endpoint.时间复杂度为 O(n),其中 n 是到最近端点的距离。 The total size of the deque does not matter.双端队列的总大小无关紧要。

Reason Why原因

The implementation of deque is a doubly-linked list of fixed length blocks. deque的实现是一个固定长度块的双向链表。 Deletion of an element requires individually moving all of the elements between the deleted point and the nearest endpoint.删除一个元素需要单独移动删除点和最近端点之间的所有元素。

Illustration插图

Consider the following example:考虑以下示例:

>>> d = deque('abcdefghijklmnop')
>>> del d[3]

For illustration purposes, assume a block size of three (the actual block size is 64) for the following data layout:出于说明目的,假设以下数据布局的块大小为 3(实际块大小为 64):

ab  ⇄  cde  ⇄  fgh  ⇄  ijk  ⇄  lmn  ⇄  op     # State before deletion
        ×                                     # Step 1, delete "d"
ab  ⇄  c-e  ⇄  fgh  ⇄  ijk  ⇄  lmn  ⇄  op     
       →                                      # Step 2, move "c" to right 
ab  ⇄  -ce  ⇄  fgh  ⇄  ijk  ⇄  lmn  ⇄  op  
 →                                            # Step 3, move "b" to right
a-  ⇄  bce  ⇄  fgh  ⇄  ijk  ⇄  lmn  ⇄  op  
→                                             # Step 4, move "a" to right
 a  ⇄  bce  ⇄  fgh  ⇄  ijk  ⇄  lmn  ⇄  op     # Final state after deletion     

As you can see, the data elements between the deleted element and the end-point all have to move over by one to the right.如您所见,已删除元素和端点之间的数据元素都必须向右移动一个。

If "k" were being deleted, the elements "lmnop" would all move one the the left.如果“k”被删除,元素“lmnop”将全部向左移动一位。 The algorithm is smart enough to work towards the closest end point.该算法足够聪明,可以朝着最近的端点工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM