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 找出数据流的中位数的更多相关文章

  1. [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 ...

  2. [LeetCode] 295. Find Median from Data Stream ☆☆☆☆☆(数据流中获取中位数)

    295. Find Median from Data Stream&数据流中的中位数 295. Find Median from Data Stream https://leetcode.co ...

  3. 剑指offer 最小的k个数 、 leetcode 215. Kth Largest Element in an Array 、295. Find Median from Data Stream(剑指 数据流中位数)

    注意multiset的一个bug: multiset带一个参数的erase函数原型有两种.一是传递一个元素值,如上面例子代码中,这时候删除的是集合中所有值等于输入值的元素,并且返回删除的元素个数:另外 ...

  4. leetcode@ [295]Find Median from Data Stream

    https://leetcode.com/problems/find-median-from-data-stream/ Median is the middle value in an ordered ...

  5. [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 ...

  6. LeetCode——295. Find Median from Data Stream

    一.题目链接: https://leetcode.com/problems/find-median-from-data-stream 二.题目大意: 给定一段数据流,要求求出数据流中的中位数,其中数据 ...

  7. 【LeetCode】295. Find Median from Data Stream 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 大根堆+小根堆 日期 题目地址:https://le ...

  8. 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 ...

  9. [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 ...

随机推荐

  1. 项目alpha冲刺-测试

    作业要求 这个作业属于哪个课程 软件工程1916-W(福州大学) 这个作业要求在哪里 项目Alpha冲刺 团队名称 基于云的胜利冲锋队 项目名称 云评:高校学生成绩综合评估及可视化分析平台 这个作业的 ...

  2. sqoop从oracle数据库抽取数据,导入到hive

    环境: hadoop-2.7.5 sqoop-1.4.7 zookeeper-3.4.10 hive-2.3.3 (使用mysql配置元数据库) jdk1.8.0_151 oracle 11.2.0. ...

  3. postgres高可用学习篇三:haproxy+keepalived实现postgres负载均衡

    环境: CentOS Linux release 7.6.1810 (Core) 内核版本:3.10.0-957.10.1.el7.x86_64 node1:192.168.216.130 node2 ...

  4. Python 02 编写代码

    原文:https://www.cnblogs.com/jimmy-share/p/9784219.html 方式: 交互式编程:打开python.exe文件后,直接输入代码即可.文件的位置(我本地): ...

  5. pyqt5 + pyinstaller 制作爬虫小程序

    环境:mac python3.7 pyqt5 pyinstaller ps: 主要是熟悉pyqt5, 加入了单选框 输入框 文本框 文件夹选择框及日历下拉框 效果图: pyqt5 主程序文件 # -* ...

  6. 均值不等式中的一则题目$\scriptsize\text{$(a+\cfrac{1}{a})^2+(b+\cfrac{1}{b})^2\ge \cfrac{25}{2}$}$

    例题已知正数\(a.b\)满足条件\(a+b=1\),求\((a+\cfrac{1}{a})^2+(b+\cfrac{1}{b})^2\)的最小值: 易错方法\((a+\cfrac{1}{a})^2+ ...

  7. 【loj2263】【CTSC2017】游戏

    题目 小\(R\)和小\(B\)一共完了\(n\)局游戏,第一局小\(R\)获胜的概率为\(p_i\),没有平局,对于第$ i $局游戏: 如果第\(i-1\)局游戏小$ R \(获胜,那么第 局游戏 ...

  8. mysql 创建时间字段

    alter table table1 add order_date datetime null; mysql> select * from table1; +----------+------- ...

  9. kerberos 配置错误记录

    服务端错误记录: 1.服务端在创建数据库的时候报如下错误: # kdb5_util -s -r HADOOP.HOME 错误提示:kdb5_util: Improper format of Kerbe ...

  10. D3.js的v5版本入门教程(第七章)—— 比例尺的使用

    D3.js的v5版本入门教程(第七章) 比例尺在D3.js中是一个很重要的东西,我们可以这样理解d3.js中的比例尺——一种映射关系,从domain映射到range域(为什么会是domain和rang ...