[LeetCode] Find Median from Data Stream
来源:互联网 发布:问道登陆器源码 编辑:程序博客网 时间:2024/06/06 00:38
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
代码如下:
public class MedianFinder {PriorityQueue<Integer> max;PriorityQueue<Integer> min; /** initialize your data structure here. */ public MedianFinder() { max=new PriorityQueue<Integer>(1000,Collections.reverseOrder()); min=new PriorityQueue<Integer>(); } public void addNum(int num) { if(min.isEmpty()||min.peek()<num) min.add(num); else max.add(num); if(min.size()<max.size()) min.add(max.poll()); if(max.size()<min.size()-1) max.add(min.poll()); } public double findMedian() { if(max.size()==min.size()) return (max.peek()+min.peek())/2.0; else return min.peek(); }}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
阅读全文
1 0
- Find Median from Data Stream leetcode 295
- LeetCode 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 -- Find Median from Data Stream
- leetcode之Find Median from Data Stream
- [LeetCode] Find Median from Data Stream
- [leetcode][C++]Find Median from Data Stream
- LeetCode Find Median from Data Stream 堆
- leetcode Find Median from Data Stream
- [LeetCode]Find Median from Data Stream
- leetcode笔记: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:Find Median from Data Stream
- LeetCode 295. Find Median from Data Stream
- 虚拟机和linux一些简单的命令
- javascript的面向对象见解
- qsort快速排序
- matlab 图像显示 命令 image imshow
- ideal常用设置
- [LeetCode] Find Median from Data Stream
- Android——自定义ViewPager指示器
- HTML5学习笔记
- 【啊哈!算法】算法10:二叉树
- displayposition 和 float 的相互关系
- 欢迎使用CSDN-markdown编辑器
- scala 枚举类
- Spring Boot大纲
- 欢迎使用CSDN-markdown编辑器