双端队列在 python 中随机访问 O(n) 而在 C++ 中为 O(1),为什么?
Deque random acces O(n) in python while O(1) in C++, why?
C++ deque:
Random access - constant O(1)
Python deque:
Indexed access is O(1) at both ends but slows to O(n) in the middle.
如果我没有遗漏任何东西,对于 python 和 C++ 中的双端队列,其他一切都同样快,至少在复杂性方面如此。在某些情况下,有什么可以使 python 的双端队列更好吗?如果没有,他们为什么不直接切换到 C++ 所拥有的?
免责声明:这个答案主要是从 Jeff 的评论中得到启发,并且答案已经在 Why is a deque implemented as a linked list instead of a circular array ?
中 post 编辑
你的问题本质上是不同的,但上面的标题本身就是一个答案:在Python中,模块collections.deque在访问中间项时具有线性时间复杂度,因为它已实现使用链表。
来自 pydoc:
A list-like sequence optimized for data accesses near its endpoints.
现在,如果您想知道为什么选择这个实现,答案已经在 Jeff 指出的 post 中提供。
因为 Deque 是一种数据结构,应该以特定方式使用,由第一个或最后一个元素访问,
但是 python 有时会用它的数据结构做一些奇怪的事情并给它们添加更多的功能,或者使用组合数据结构
在这种情况下 python 具有函数
remove(value)
#Remove the first occurrence of value. If not found, raises a ValueError.
这允许您访问双端队列中间的数据结构元素,它不是此数据结构的 "core" 操作,
导致 "but slows to O(n) in the middle. "
因为在这种情况下它的行为就像一个数组(一个一个地检查值)
C++ deque:
Random access - constant O(1)
Python deque:
Indexed access is O(1) at both ends but slows to O(n) in the middle.
如果我没有遗漏任何东西,对于 python 和 C++ 中的双端队列,其他一切都同样快,至少在复杂性方面如此。在某些情况下,有什么可以使 python 的双端队列更好吗?如果没有,他们为什么不直接切换到 C++ 所拥有的?
免责声明:这个答案主要是从 Jeff 的评论中得到启发,并且答案已经在 Why is a deque implemented as a linked list instead of a circular array ?
中 post 编辑你的问题本质上是不同的,但上面的标题本身就是一个答案:在Python中,模块collections.deque在访问中间项时具有线性时间复杂度,因为它已实现使用链表。
来自 pydoc:
A list-like sequence optimized for data accesses near its endpoints.
现在,如果您想知道为什么选择这个实现,答案已经在 Jeff 指出的 post 中提供。
因为 Deque 是一种数据结构,应该以特定方式使用,由第一个或最后一个元素访问, 但是 python 有时会用它的数据结构做一些奇怪的事情并给它们添加更多的功能,或者使用组合数据结构
在这种情况下 python 具有函数
remove(value)
#Remove the first occurrence of value. If not found, raises a ValueError.
这允许您访问双端队列中间的数据结构元素,它不是此数据结构的 "core" 操作,
导致 "but slows to O(n) in the middle. "
因为在这种情况下它的行为就像一个数组(一个一个地检查值)