Python heapq
python heapq 是 binary heap 的变种,见 binary heap
How to customize the heap order?
Have each element on the heap to be a tuple, with the first tuple element being one that accepts normal Python comparisons.
Eg.
基本用法
Time complexity
heapq.heapify(x): O(k)
heapq.heappush(heap, item): O(logk)
heapq.heappop(heap): O(logk)
对于 nsmallest 和 nlargest 的时间复杂度有点疑惑,找了些资料,就源代码而言,应该是 O(nlogt),然而有一种说法是 O(t+n),见 How does heapq.nlargest work?
source code,2.7 和 3.4 这一部分是一样的。
例题
23. Merge k Sorted Lists
Problem
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution
|
|