原题地址(困难)
方法1—优先队列/堆
思路
这道题没啥好说的,直接上优先队列。
开始我想的是用一个列表,然后不断插入,维持列表有序,所以时间复杂度在O(n),结果会超时。
这道题就是为优先队列量身定制,时间复杂度为O(logN)。
也是通过这道题学习了c++和Python优先队列的使用
代码
c++
class MedianFinder {priority_queue<int> lo; // max heappriority_queue<int, vector<int>, greater<int>> hi; // min heappublic:// Adds a number into the data structure.void addNum(int num){lo.push(num); // Add to max heaphi.push(lo.top()); // balancing steplo.pop();if (lo.size() < hi.size()) { // maintain size propertylo.push(hi.top());hi.pop();}}// Returns the median of current data streamdouble findMedian(){return lo.size() > hi.size() ? (double) lo.top() : (lo.top() + hi.top()) * 0.5;}};
Python
要注意Python只有小顶堆,没有大顶堆,所以把元素取负值,才能实现大顶堆效果。
class MedianFinder:def __init__(self):"""initialize your data structure here."""self.count = 0self.maxHeap = []self.minHeap = []def addNum(self, num: int) -> None:self.count += 1# python只有小顶堆,所以把num取负传入,才可实现大顶堆效果heapq.heappush(self.maxHeap, -num)maxHeap_top = -heapq.heappop(self.maxHeap) # 取大顶堆top元素heapq.heappush(self.minHeap, maxHeap_top) # 传入小顶堆if self.count & 1: # 如果元素总数为奇数,则让大顶堆多一个元素heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))def findMedian(self) -> float:if self.count & 1:return -self.maxHeap[0]else:return (-self.maxHeap[0] + self.minHeap[0]) * 0.5
时空复杂度
时间复杂度O(logN)
空间复杂度O(N)
