[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 ...
随机推荐
- Java.io.tmpdir介绍
System.getproperty(“java.io.tmpdir”)是获取操作系统缓存的临时目录,不同操作系统的缓存临时目录不一样, 在Windows的缓存目录为:C:\Users\登录用户~1\ ...
- easyui dialog 设置弹窗位于页面中间
原文链接:https://my.oschina.net/jingyao/blog/776603 此方法为解决页面含有滚动条时,弹窗位置错误问题,此方法可将带滚动条页面中弹窗显示于页面中间. $(&qu ...
- keyword (this and arguments) in function --- 涉及递归
arguments 就像一个数组一样,包含了传递给这个函数的参数 , 以上部分为this的介绍,注意arguments.callee 属性 ,可用于递归调用,其代表的是 : 当前正在运行函数的引用 ...
- Ubuntu 14.04.2配置rsync
ubuntu系统自带rsync,首先配置/etc/default/rsync,启用daemon模式 修改/etc/rsyncd.conf配置文件 cat /etc/rsyncd.conf # samp ...
- Celery + Redis 的探究
Celery + Redis 的探究 文本尝试研究,使用 redis 作为 celery 的 broker 时,celery 的交互操作同 redis 中数据记录的关联关系. 不在乎过程的,可以直接看 ...
- 让一个项目同时提交到码云和GitHub两个仓库
在项目目录里找到.git文件夹然后找到config文件. 打开这个文件后找到下面的代码 [remote "origin"] url = git提交地址 fetch = +refs/ ...
- (1)WIFI信号确定距离
https://blog.csdn.net/PINGER0077/article/details/79482238 ESP8266不需要修改任何库 #include "ESP8266WiFi ...
- GoCN每日新闻(2019-09-30)
GoCN每日新闻(2019-09-30) 1. 使用Sqlmock测试数据库 https://medium.com/ralali-engineering/testing-database-using- ...
- Beta冲刺(4/5)
队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 讨论校园百科究竟如何实现,并分配了任务 提交记录(全组共用) 接下来的计划 加快校园百科的进度 准备Beta版本的汇报 还 ...
- Clion下同时编写多个main函数
在你的CMakeLists.txt文件下配置,使用add_executable(),前面的一定要不一样 红色部分是描述main的,配置后运行处可以选择: