实现优先级队列(小根堆)

Posted npc-assange

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现优先级队列(小根堆)相关的知识,希望对你有一定的参考价值。

头条算法一面,记录一下

实现优先级队列(小根堆)

 1 class prioQueue:
 2     def __init__(self, elist=[]):
 3         self._elems = list(elist)
 4         if elist:
 5             self.buildheap()
 6     def siftdown(self, e,begin, end):
 7         elems, i, j, = self._elems, begin , begin*2+1
 8         while j < end:
 9             if j+1<end and elems[j+1] < elems[j]:
10                 j = j + 1         
11             if e < elems[j]:
12                 break
13             elems[i] = elems[j]
14             i, j = j , 2*j+1
15         elems[i] = e
16     def buildheap(self):
17         end = len(self._elems)
18         for i in range(end//2,-1,-1):
19             self.siftdown(self._elems[i],i,end)
20         return self._elems
21     def peek(self):                       
22         return self._elems[0]
23     def dequeue(self):
24         elems = self._elems
25         e0 = elems[0]
26         e = elems.pop()
27         if len(elems) > 0:
28             self.siftdown(e, 0 , len(elems))
29         return e0
30     def siftup(self, e, last):
31         elems , i , j = self._elems, last, (last-1)//2
32         while i > 0 and e < elems[j]:
33             elems[i] = elems[j]
34             i, j = j ,(j-1)//2
35         elems[i] = e
36     def enqueue(self, e):
37         self._elems.append(None)
38         self.siftup(e, len(self._elems)-1)
39         return self._elems

以上是关于实现优先级队列(小根堆)的主要内容,如果未能解决你的问题,请参考以下文章

介绍一下PriorityQueue,以及优先队列实现大小根堆

POJ3784 动态中位数(大根堆+小根堆+优先队列)

优先队列和哈夫曼树

Java集合与数据结构——优先级队列(堆)

数据结构_二叉树Ⅲ——堆与优先队列

图文最详细的堆解析:从二叉树到堆到解析大根堆小根堆,分析堆排序,最后实现topK经典面试问题