heapq实现的就是最小堆,如果需要实现最大堆,可以通过加上负号。
heapq.heappop(res)
heapq.heappush(res, num)
heapq.heapify() 转化成堆
1、#### 可以直接使用self.heap1[0]来代表堆顶,用nsamllest太麻烦了,时间复杂度太大
2、注意最小堆,堆顶绝对是最小的。
3、永远都是heapq开头,原本的堆放在函数里面。注意,堆在这里只是一个抽象的数据结构,还是基于list实现的。
4、其实从头开始直接 heapq.heappush和heappop最后得到的就是最小堆了。不需多余的操作。
#随便拿一个列表,heappush就可以得到一个堆了,尽管之前不是堆,也可以一起变成堆
import heapq
#向堆中插入元素,heapq会维护列表heap中的元素保持堆的性质
heapq.heappush(heap, item) # push之后还是堆
#heapq把列表x转换成堆
heapq.heapify(x)
#从堆中删除元素,返回值是堆中最小或者最大的元素
heapq.heappop(heap) # heappop面向的是堆,pop之后还是堆
#从可迭代的迭代器中返回最大的n个数,可以指定比较的key------针对列表即可
heapq.nlargest(n, iterable[, key])
#从可迭代的迭代器中返回最小的n个数,可以指定比较的key
heapq.nsmallest(n, iterable[, key])
import heapq
nums = [14, 20, 5, 28, 1, 21, 16, 22, 17, 28]
heapq.nlargest(3, nums) 列表的前n大
# [28, 28, 22]
heapq.nsmallest(3, nums) 列表的前n小
# [1, 5, 14]
a = [100, 200] #随便拿一个列表,heappush就可以得到一个堆了,尽管之前不是堆,也可以一起变成堆
heapq.heappush(a, 5)
heapq.heappush(a, 10)
heapq.heappush(a, 9)
heapq.heappush(a, 3)
heapq.heappush(a, 8)
heapq.heappush(a, 5)
heapq.heappush(a, 3)
heapq.heappop(a)
print(a) # [3, 5, 5, 9, 10, 100, 8, 200]
讲一道数据流的中位数,用一个最大堆和一个最小堆解决,最大堆的最大加上最小堆的最小,也就是我们的中位数了。所以最大堆存储的都是小于最小堆的部分,最小堆存储的都是大于最大堆的部分。
import heapq
# 1、#### 可以直接使用self.heap1[0]来代表堆顶,用nsamllest太麻烦了,时间复杂度太大
# 2、注意最小堆,堆顶绝对是最小的。
# 3、永远都是heapq开头,原本的堆放在函数里面。注意,堆在这里只是一个抽象的数据结构,还是基于list实现的。
class Solution:
def flowmedian(self , operations ):
# write code here
self.heapq1 = []
self.heapq2 = []
self.sign = 1
self.num1 = 0
self.num2 = 0
result = []
for i in range(len(operations)):
if int(operations[i][0]) == 1:
self.insert(int(operations[i][1]))
else:
result.append(self.find_mid())
return result
def insert(self, num):
if self.sign:
heapq.heappush(self.heapq2, -num)
res = -heapq.heappop(self.heapq2)
heapq.heappush(self.heapq1, res)
self.num1 += 1
self.sign = 0
else:
heapq.heappush(self.heapq1, num)
res = heapq.heappop(self.heapq1)
heapq.heappush(self.heapq2, -res)
self.num2 += 1
self.sign = 1
def find_mid(self):
if not self.num1 and not self.num2:
return -1
if self.num1 == self.num2:
#最好不要× return (heapq.nsmallest(1, self.heapq1)[0] - heapq.nsmallest(1, self.heapq2)[0])/2
return (self.heapq1[0] - self.heapq2[0]) / 2
elif self.num1 > self.num2:
return self.heapq1[0]
else:
return -self.heapq2[0]
# return -heapq.nsmallest(1, self.heapq2)[0]