295. Find Median from Data Stream 剑指offer 数据流中的中位数
来源:互联网 发布:儿童医院在线咨询网络 编辑:程序博客网 时间:2024/05/19 19:42
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:
addNum(1)addNum(2)findMedian() -> 1.5addNum(3) findMedian() -> 2.
class MedianFinder {public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { if(size&1)//奇数个 { if(!minHeap.empty()&&num>minHeap.top()) { minHeap.push(num); num=minHeap.top(); minHeap.pop(); } maxHeap.push(num); } else { if(!maxHeap.empty()&&num<maxHeap.top()) { maxHeap.push(num); num=maxHeap.top(); maxHeap.pop(); } minHeap.push(num); } size++; } double findMedian() { if(size&1) return minHeap.top(); else return static_cast<double>(minHeap.top()+maxHeap.top())/2.0; } private: priority_queue<int,vector<int>,greater<int>> minHeap;//最小堆 priority_queue<int> maxHeap;//最大堆 int size=0;};/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
阅读全文
0 0
- 295. Find Median from Data Stream 剑指offer 数据流中的中位数
- 295. Find Median from Data Stream&数据流中的中位数
- LeetCode 295. Find Median from Data Stream(数据流中位数)
- 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
- oracle触发器分类
- redis的自启设置
- DFS(深度搜索)——基于回溯法和递归
- Unity学习2 鼠标点击控制物体移动
- C++语法基础之关键字与标识符(10月4日暂存)
- 295. Find Median from Data Stream 剑指offer 数据流中的中位数
- 42. Trapping Rain Water 及类似题目 407. Trapping Rain Water II 11. Container With Most Water
- linux内核--资源管理
- 162. Find Peak Element 一次遍历或二分查找
- 【python】100行代码python爬虫程序,抓取网站图片存储本地(附:中文链接解决)
- curl windows下编译lib
- jenkins加docker自动化部署
- 输出四位数各位上的数字
- 使用 IDEA 整合 SSH 发生 Mapping (RESOURCE) not found 错误