295. Find Median from Data Stream
来源:互联网 发布:阿尔法算法 编辑:程序博客网 时间:2024/06/05 23:50
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
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
public class MedianFinder { PriorityQueue<Double> maxHeap; PriorityQueue<Double> minHeap; /** initialize your data structure here. */ public MedianFinder() { maxHeap = new PriorityQueue<Double>(); minHeap = new PriorityQueue<Double>(); } public void addNum(int num) { minHeap.add((double)num); maxHeap.add(-minHeap.poll()); if (maxHeap.size() > minHeap.size() + 1) { minHeap.add((double)-maxHeap.poll()); } } public double findMedian() { return minHeap.size() == maxHeap.size()? (minHeap.peek() - maxHeap.peek()) / 2: -maxHeap.peek(); }}/** * 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
- 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
- [hard]295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- centos学习:理解环境变量 临时、永久
- 模仿easyUI 实现tab切换
- Java精选笔记_Java入门
- shell脚本.example
- 三种快速排序以及快速排序的优化
- 295. Find Median from Data Stream
- 获取HttpServletRequest请求消息头、消息行信息
- HDU 5201 The Monkey King (容斥+数学组合+隔板法)
- java第五天学习知识汇总
- Markov过程(马尔科夫过程)
- Unity角色技能及技能编辑器设计之概念篇
- img元素srcset属性浅析
- 智慧仓储篇 1 —— 仓储业务分析
- 大小端模式介绍及两种检测方式