[LeetCode] 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.
For example,
[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.
Example:
- addNum(1)
- addNum(2)
- findMedian() -> 1.5
- addNum(3)
- findMedian() -> 2
此题要找出数据流的中位数,数据流由无序整数组成,并且数据流是在变化的。中位数的定义是,如果数字个数为偶数,中位数就是中间两个数的平均数,如果是奇数,中位数是中间那个数字。
解法1: 最简单的想法是,每进来一个数字后,插入排序整个数组,保持数组是有序的,然后分奇偶的情况找到中位数。此方法不高效。
解法2: 堆Heap,将进来的数据流分成大小两个堆,分别保存堆的前半部分和后半部分,大堆是最小数字在堆顶,小堆是最大数在堆顶。取中间值时,根据两个堆的数字个数,如果个数相同,就各取堆顶数字取平均数就是中间数,如果有一个堆数字多1,中间数就是这个堆顶数字。
Java:
- class MedianFinder {
- PriorityQueue<Integer> maxHeap;//lower half
- PriorityQueue<Integer> minHeap;//higher half
- public MedianFinder(){
- maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
- minHeap = new PriorityQueue<Integer>();
- }
- // 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() {
- if(maxHeap.size()==minHeap.size()){
- return (double)(maxHeap.peek()+(minHeap.peek()))/2;
- }else{
- return maxHeap.peek();
- }
- }
- }
Python:
- from heapq import heappush, heappop
- class MedianFinder:
- def __init__(self):
- """
- Initialize your data structure here.
- """
- self.__max_heap = []
- self.__min_heap = []
- def addNum(self, num):
- """
- Adds a num into the data structure.
- :type num: int
- :rtype: void
- """
- # Balance smaller half and larger half.
- if not self.__max_heap or num > -self.__max_heap[0]:
- heappush(self.__min_heap, num)
- if len(self.__min_heap) > len(self.__max_heap) + 1:
- heappush(self.__max_heap, -heappop(self.__min_heap))
- else:
- heappush(self.__max_heap, -num)
- if len(self.__max_heap) > len(self.__min_heap):
- heappush(self.__min_heap, -heappop(self.__max_heap))
- def findMedian(self):
- """
- Returns the median of current data stream
- :rtype: float
- """
- return (-self.__max_heap[0] + self.__min_heap[0]) / 2.0 \
- if len(self.__min_heap) == len(self.__max_heap) \
- else self.__min_heap[0]
C++:
- class MedianFinder {
- public:
- // Adds a number into the data structure.
- void addNum(int num) {
- small.push(num);
- large.push(-small.top());
- small.pop();
- if (small.size() < large.size()) {
- small.push(-large.top());
- large.pop();
- }
- }
- // Returns the median of current data stream
- double findMedian() {
- return small.size() > large.size() ? small.top() : 0.5 *(small.top() - large.top());
- }
- private:
- priority_queue<long> small, large;
- };
All LeetCode Questions List 题目汇总
[LeetCode] 295. Find Median from Data Stream 找出数据流的中位数的更多相关文章
- [LeetCode] 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 ...
- [LeetCode] 295. Find Median from Data Stream ☆☆☆☆☆(数据流中获取中位数)
295. Find Median from Data Stream&数据流中的中位数 295. Find Median from Data Stream https://leetcode.co ...
- 剑指offer 最小的k个数 、 leetcode 215. Kth Largest Element in an Array 、295. Find Median from Data Stream(剑指 数据流中位数)
注意multiset的一个bug: multiset带一个参数的erase函数原型有两种.一是传递一个元素值,如上面例子代码中,这时候删除的是集合中所有值等于输入值的元素,并且返回删除的元素个数:另外 ...
- leetcode@ [295]Find Median from Data Stream
https://leetcode.com/problems/find-median-from-data-stream/ Median is the middle value in an ordered ...
- [leetcode]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 ...
- LeetCode——295. Find Median from Data Stream
一.题目链接: https://leetcode.com/problems/find-median-from-data-stream 二.题目大意: 给定一段数据流,要求求出数据流中的中位数,其中数据 ...
- 【LeetCode】295. Find Median from Data Stream 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 大根堆+小根堆 日期 题目地址:https://le ...
- 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 ...
- [LC] 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 ...
随机推荐
- MySQL的增、删、改、查
数据库的常用命令以及作用 用法 作用 CREATE database 数据库名称. 创建新的数据库 DESCRIBE 表单名称; 描述表单 UPDATE 表单名称 SET attribute=新值 W ...
- 数组函数some、every、find、filter、map、forEach有什么区别
- ARTS-week5
Algorithm 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组.说明:初始化 nums1 和 nums2 的元素数量分别 ...
- formData上传文件
需要将选中的xml传到后台,通过xslt转换为html html: <form id="uploadForm" enctype="multipart/form-da ...
- Spark-源码分析03-SubmitTask
1.Rdd rdd中 reduce.fold.aggregate.collect.count这些方法 都会调用 sparkContext.runJob ,这些方法称之为Action 触发提交Job d ...
- 2019-2020-1 20199302《Linux内核原理与分析》第八周作业
一.上课学习笔记 1.shell作用:①运行程序 ②重定向(输入/输出重定向) ③可编程(写脚本) 执行一个c程序时,如果切进另一个进程,会进入该进程而切不回原进程,所以需要为调用的进程创一个子进程. ...
- S1_搭建分布式OpenStack集群_11 虚拟机创建
一.创建网络环境环境变量生效一下创建一个网络:# openstack network create --share --external \--provider-physical-network ph ...
- webuploader解决大文件断点续传
文件夹数据库处理逻辑 public class DbFolder { JSONObject root; public DbFolder() { this.root = new JSONObject() ...
- C# 监测每个方法的执行次数和占用时间(测试5)
又找到了一个bug 测试的类: public class Class11_1 { public virtual List<int> test2_1(List<tb_SensorRec ...
- 2017.10.2 国庆清北 D2T1 (a*b)|x
在电脑上后面仨点过不了,要用I64d,lld会炸.但是洛谷上要用lld,LINUX系统没有I64d /* 求一个数对满足 (a*b)|n,也就是求三个数 a*b*c=n,那么求1~n之间的,就是a*b ...