[hard]295. Find Median from Data Stream
来源:互联网 发布:大数据的关键技术 编辑:程序博客网 时间:2024/05/04 05:57
295. Find Median from Data Stream
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.
Examples:[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.
For example:
add(1)add(2)findMedian() -> 1.5add(3) findMedian() -> 2
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Solution:
It's a super classic problem, maintain two heaps. view codes to see my tricks.
class MedianFinder {private: priority_queue <int> tail_half; priority_queue <int, vector <int>, greater<int> > head_half;public: // Adds a number into the data structure. void addNum(int num) { tail_half.push(num); head_half.push(tail_half.top()); tail_half.pop(); if (head_half.size() > tail_half.size()) { tail_half.push(head_half.top()); head_half.pop(); } } // Returns the median of current data stream double findMedian() { size_t size = head_half.size() + tail_half.size(); if (size & 1) return tail_half.top(); return (head_half.top() + tail_half.top()) / 2.0; }};
0 0
- [hard]295. Find Median from Data Stream
- Leetcode 295. Find Median from Data Stream (Hard) (cpp)
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- Leetcode 295. Find Median from Data Stream
- Leetcode - 295. Find Median From Data Stream
- [leetcode] 295. Find Median from Data Stream
- LeetCode 295. Find Median from Data Stream
- leetcode 295. Find Median from Data Stream
- LeetCode 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- leetcode.295. Find Median from Data Stream
- 295. Find Median from Data Stream
- [leetcode] 295. Find Median from Data Stream
- [LeetCode]--295. Find Median from Data Stream
- leetcode:295. Find Median from Data Stream
- leetcode 295.Find Median from Data Stream
- 295. Find Median from Data Stream
- Android性能优化篇(三),常客Handler、Thread泄露
- linux命令——分割文件、合并文件
- GLPK 安装配置与使用
- Android 特效库 - 仿QQ汽泡
- bzoj2242
- [hard]295. Find Median from Data Stream
- javascript函数中的返回值
- openwrt之ubus
- Android Tween Animation动画效果详解
- POJ3069Saruman's Army(贪心)
- web基础阶段总结
- python学习
- Go语言 bufio库 使用
- UIGraphicsBeginImageContext