题目
相同题目:剑指:数据流中的中位数
法1:堆
python基于最大堆,最小堆来做,最大堆,最小堆使用数据结构heapq,该结构默认是最小堆。最大堆实现介绍:
在 Python 的 heapq 模块中,默认实现的是小根堆(最小堆),但可以通过对元素取反的方式,间接实现 最大堆(大根堆)。以下是具体实现方法及示例:
(1)实现原理
数值取反:将元素的值取负数存入堆,使堆顶元素为原数据的最大值。
操作时还原:取出元素后,再次取反恢复原始值。
(2)代码示例
- 插入与弹出元素
import heapq
# 初始化最大堆(通过存储负数实现)
max_heap = []
data = [3, 1, 4, 2]
# 插入元素(数值取反)
for num in data:
heapq.heappush(max_heap, -num) # 存储负数
# 弹出最大值(取反还原)
largest = -heapq.heappop(max_heap)
print(largest) # 输出: 4(原数组最大值)
2.直接堆化列表
data = [3, 1, 4, 2]
# 将列表元素取反后堆化
neg_data = [-x for x in data]
heapq.heapify(neg_data)
# 弹出最大值
largest = -heapq.heappop(neg_data)
print(largest) # 输出: 4
代码实现:
class MedianFinder:
def __init__(self):
self.left = [] # 大根堆
self.right = [] # 小根堆
def addNum(self, num: int) -> None:
if len(self.left) == len(self.right): # 添加元素到left
heapq.heappush(self.left, -heapq.heappushpop(self.right, num))
else: # 添加元素到right
heapq.heappush(self.right, -heapq.heappushpop(self.left, -num))
def findMedian(self) -> float:
if len(self.left) > len(self.right):
return -self.left[0]
else:
return (self.right[0] - self.left[0]) / 2
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
法2:优先队列
优先队列介绍:https://blog.youkuaiyun.com/weixin_73616913/article/details/131361059
必须掌握的算法!!!
class MedianFinder {
PriorityQueue<Integer> queueBig;
PriorityQueue<Integer> queueSmall;
public MedianFinder() {
queueBig = new PriorityQueue<>((a, b) -> b.compareTo(a));
queueSmall = new PriorityQueue<>();
}
public void addNum(int num) {
if (queueBig.size() == queueSmall.size()) {
queueSmall.offer(num);
queueBig.offer(queueSmall.poll());
} else {
queueBig.offer(num);
queueSmall.offer(queueBig.poll());
}
}
public double findMedian() {
if (queueBig.size() != queueSmall.size()) {
return queueBig.peek();
} else {
return ((double) (queueBig.peek() + queueSmall.peek())) / 2.0;
}
}
}