Python:插入列表比 O(N) 更快?
Python: insert into list faster than O(N)?
我有一个排序列表 L,我有一个二进制搜索来确定在列表中的哪个位置插入一个元素,这样生成的列表仍然是有序的。
然而L.insert(index,object)需要O(N)的时间复杂度。
L 是否有另一种数据结构可以达到同样的目的,但允许更快的插入?
查看 blist 模块。
https://pypi.python.org/pypi/blist/
它要求 O(log n) 插入。
用法:
x = #list contents
y = blist(x)
y.insert(index, object) #now works in O(log n)
向 sortedcontainers.SortedList
大声喊叫。这将使您的列表自动保持有序,插入时间很快。
from sortedcontainers import SortedList
mylist = SortedList([1, 2, 4, 5])
mylist.add(3)
mylist
#>>> SortedList([1, 2, 3, 4, 5], load=1000)
SortedList
insertions are amortized O(sqrt n)
, or O(cbrt n)
with different choices of parameters, but it scales better than blist
, which is O(log n)
, because the constants are much better. There is a very in-depth look at performance on their website.
或者,您可能需要 priority queue in which case you can get potentially-faster inserts with the heapq
module。
我有一个排序列表 L,我有一个二进制搜索来确定在列表中的哪个位置插入一个元素,这样生成的列表仍然是有序的。
然而L.insert(index,object)需要O(N)的时间复杂度。
L 是否有另一种数据结构可以达到同样的目的,但允许更快的插入?
查看 blist 模块。
https://pypi.python.org/pypi/blist/
它要求 O(log n) 插入。
用法:
x = #list contents
y = blist(x)
y.insert(index, object) #now works in O(log n)
向 sortedcontainers.SortedList
大声喊叫。这将使您的列表自动保持有序,插入时间很快。
from sortedcontainers import SortedList
mylist = SortedList([1, 2, 4, 5])
mylist.add(3)
mylist
#>>> SortedList([1, 2, 3, 4, 5], load=1000)
SortedList
insertions are amortized O(sqrt n)
, or O(cbrt n)
with different choices of parameters, but it scales better than blist
, which is O(log n)
, because the constants are much better. There is a very in-depth look at performance on their website.
或者,您可能需要 priority queue in which case you can get potentially-faster inserts with the heapq
module。