[leetcode] Find Median from Data Stream
2015-11-01 20:27
337 查看
题目:
分析:维护一个大顶堆(maxHeap)和一个小顶堆(minHeap),其中大顶堆的元素都小于小顶堆的元素,比如add 2, 3, 4, 5, 6后,堆内的元素如下:
当maxHeap.size() != minHeap.size()时,返回maxHeap.peek();当maxHeap.size() == minHeap.size()时,返回(maxHeap.peek() + minHeap.peek())/2.
Java代码如下:
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.5 add(3) findMedian() -> 2
分析:维护一个大顶堆(maxHeap)和一个小顶堆(minHeap),其中大顶堆的元素都小于小顶堆的元素,比如add 2, 3, 4, 5, 6后,堆内的元素如下:
maxHeap 4 3 2 minHeap 5 6
当maxHeap.size() != minHeap.size()时,返回maxHeap.peek();当maxHeap.size() == minHeap.size()时,返回(maxHeap.peek() + minHeap.peek())/2.
Java代码如下:
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; }; }); // Adds a number into the data structure. public void addNum(int num) { maxHeap.offer(num); minHeap.offer(maxHeap.poll()); if (maxHeap.size() < minHeap.size()) { maxHeap.offer(minHeap.poll()); } } // Returns the median of current data stream public double findMedian() { return maxHeap.size() == minHeap.size() ? (double)(maxHeap.peek()+minHeap.peek())/2 : maxHeap.peek(); }
相关文章推荐
- 开机时忘记乌班图密码
- 什么是EXC_BAD_ACCESS以及如何调试
- Apache学习笔记(1)——http协议
- ForRobot
- loadrunner11.0安装与破解
- sqlserver 迁移到mysql
- 如何获得servletConfig对象和servletContext对象以及通过这两个对象获得初始化参数
- swift 实现对UItableView下cell中内容的搜索(2)
- 第五篇 读后感
- NENU_CS_segment_tree
- linux下Hadoop在Eclipse的配置和使用
- 解析python中:if __name__=='__main__':
- SAP FICO hande汉得培训资料---IV 资产模块篇PDF 电子版
- test
- spark wordCount单词计数及原理解析
- 数组元素必须具有相同的数据类型?
- hello world
- 用html和css写简单的静态网页
- android自定义控件(理论知识学习 +自定义属性的讲解)
- Foundation 之 NSSet和NSMutableSet以及NSIndexSet和NSMutableIndexSet