leetcode295 - Find Median from Data Stream - hard
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
- void addNum(int num) - Add a integer number from the data stream to the data structure.
- double findMedian() - Return the median of all elements so far.
Example:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
Follow up:
- If all integer numbers from the stream are between 0 and 100, how would you optimize it?
- If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
用两个heap做,max heap维护比median小的数,从小到大排,top就是矮子里的高个-最靠近median的;min heap维护比median大的数,从大到小排,top就是高个里的矮子-也是最靠近median的。同时要保证两个heap大小最多差1,这样size大的那个的top或者两个top的平均数就是median。
实现:Time O(logn)- heap access Space O(n)
class MedianFinder { priority_queue<int> smallerHalf; priority_queue<int, vector<int>, greater<int>> largerHalf; public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { smallerHalf.push(num); int largestAmongSmaller = smallerHalf.top(); smallerHalf.pop(); largerHalf.push(largestAmongSmaller); if (largerHalf.size() > smallerHalf.size()){ int smallestAmongLarger = largerHalf.top(); smallerHalf.push(smallestAmongLarger); largerHalf.pop(); } } double findMedian() { if (smallerHalf.size() == largerHalf.size()) return 0.5*(smallerHalf.top() + largerHalf.top()); else return smallerHalf.top(); } };

浙公网安备 33010602011771号