码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-02 20:34:22      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:build   down   init   span   turn   one   EAP   while   append   

头条算法一面,记录一下

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

 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

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

标签:build   down   init   span   turn   one   EAP   while   append   

原文地址:https://www.cnblogs.com/NPC-assange/p/12141762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!