Indeed, Python no separate stack type, and only a few functions of the module stack operation contains. This module is called heapq (where q represents the queue), a small top default heap. Python is not the big top of the heap implementation.
Commonly used functions
function | description |
---|---|
heappush(heap, x) | The pile press-x |
heappop(heap) | From the pop-up stack smallest elements (top element) |
heapify([1,2,3]) | Make a list of characteristics with heap |
heapreplace(heap, x) | Pop smallest elements (top element), and the stack pressed x |
nlargest(n, iter) | Iter returns the largest element in the n |
nsmallest(n, iter) | Iter returns the smallest element of n |
heappop pop smallest element (always at index 0, \ stack), and to ensure that the smallest remaining element at index 0 (the stack holding feature).
heapreplace equal to heappop then heappush, but calls were faster than them.
Stack operation time complexity, the following is a heap of implementation: binary heap, Fibonacci heap, Fibonacci heap ...... strict, common module is used in Fibonacci heap "
Code Example:
from heapq import *
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.q = []
for x in nums:
self.add(x)
def add(self, val: int) -> int:
if len(self.q) < self.k: # 堆没满,加入堆
heappush(self.q, val)
elif val > self.q[0]: # val大于堆顶元素(第K大),踢掉堆顶元素,加入val
heapreplace(self.q, val)
return self.q[0] # 堆顶
import heapq
a = [2,4,1,5,6,3]
heapq.heapify(a)
print(a) # [1, 4, 2, 5, 6, 3]
import heapq
a = [2,4,1,5,6,3]
heapq.heapify(a)
b = heapq.heappop(a)
print(a) # [2, 4, 3, 5, 6]
print(b) # 1