# 算法：堆（优先队列）

#### python实现

class HEAPQ:
# 最小堆
def __init__(self, l):
self.l = l
self.build()

def build(self):
n = len(self.l)
end = n // 2
for i in range(end, -1, -1):
self.update(i)

def update(self, i):
l = self.l
n = len(l)
idx = i
if 2 * i + 1 < n and l[2 * i + 1] < l[idx]:
idx = 2 * i + 1
if 2 * i + 2 < n and l[2 * i + 2] < l[idx]:
idx = 2 * i + 2
if idx != i:
l[i], l[idx] = l[idx], l[i]
self.update(idx)

def push(self, x) -> int:
l = self.l
l.append(x)
i = len(l)-1
while i != 0:
parent = (i-1) // 2
# 父节点大于 则上浮
if l[parent] > l[i]:
l[parent], l[i] = l[i], l[parent]
i = parent
else:
break

def pop(self):
l = self.l
n = len(l)
l[0], l[n - 1] = l[n - 1], l[0]
t = l.pop()
self.update(0)
return t

def top(self):
return self.l[0]


215. 数组中的第K个最大元素

#### 面试题 17.09. 第 k 个数

class Solution:
def getKthMagicNumber(self, k: int) -> int:
l = [1]
ss = set()
tt = (3,5,7)
for i in range(1,k):
t = heapq.heappop(l)
for x in tt:
if t*x not in ss:
heapq.heappush(l, t*x)
return l[0]



#### 面试题 17.20. 连续中值

void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。

class MedianFinder:

def __init__(self):
self.max_heapq = []  # 最大堆个数大于等于最小堆
self.min_heapq = []
def addMax(self, l, x):
l.append(x)
n = len(l)
start = n-1
while start > 0:
p = (start-1)//2
if l[p] < l[start]:
l[p], l[start] = l[start],l[p]
start = p
else:
break

def addMin(self, l, x):
l.append(x)
n = len(l)
start = n-1
while start > 0:
p = (start-1)//2
if l[p] > l[start]:
l[p], l[start] = l[start],l[p]
start = p
else:
break
def updateMax(self, l,i, n):
idx = i
if i*2+1<n and l[2*i+1] > l[i]:
idx = i*2+1
if i*2+2<n and l[2*i+2] > l[idx]:
idx = i*2+2
if idx!=i:
l[idx], l[i] = l[i], l[idx]
self.updateMax(l, idx, n)
def updateMin(self, l,i, n):
idx = i
if i*2+1<n and l[2*i+1] < l[i]:
idx = i*2+1
if i*2+2<n and l[2*i+2] < l[idx]:
idx = i*2+2
if idx!=i:
l[idx], l[i] = l[i], l[idx]
self.updateMin(l, idx, n)
def popMax(self, l):
n = len(l)
l[0], l[n-1] = l[n-1], l[0]
t = l.pop()
self.updateMax(l, 0, n-1)
return t
def popMin(self, l):
n = len(l)
l[0], l[n-1] = l[n-1], l[0]
t = l.pop()
self.updateMin(l, 0, n-1)
return t

def addNum(self, num: int) -> None:
if not self.max_heapq:
self.max_heapq.append(num)
return
if num <= self.max_heapq[0]:
else:
if len(self.min_heapq) > len(self.max_heapq):
elif len(self.max_heapq)-len(self.min_heapq) >1:

def findMedian(self) -> float:
if len(self.max_heapq) == len(self.min_heapq):
return (self.max_heapq[0] + self.min_heapq[0])/2
else:
return self.max_heapq[0]

• 3
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
07-25 688
05-03 2369
04-17 1373
09-05 4380
04-12
04-16
05-17 781
05-15 753
05-13 628
05-13 968
05-15 784
05-14 523
05-17 345
05-15 1011
05-13 355

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。