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

题意:

给定一堆数据,求其中位数(将数据升序排列。若数据个数为奇,则正中为中位数;若数据个数为偶,则正中两数平均值为中位数)

思路:

显然若数据大,排序再找中位数是不现实的。

用PriorityQueue分别建maxHeap, minHeap, 并保证maxHeap.size() - minHeap.size() <=1

如此,当最终maxHeap.size() = minHeap.size()  说明数据个数为偶,取两个Heap的peek值的平均值

当最终maxHeap.size() > minHeap.size()  说明数据个数为奇,取maxHeap.peek

扫数据中的每个元素

[6,  10,  2,  6,  5,  0,  6,  3]

^  若maxHeap.isEmpty() || 当前元素 < maxHeap.peek() , 扔到maxHeap里去

[6,  10,  2,  6,  5,  0,  6,  3]

^ 若当前元素 >= maxHeap.peek() , 扔到minHeap里去

[6,  10,  2,  6,  5,  0,  6,  3]

^   当前元素 < maxHeap.peek() , 扔到maxHeap里去

[6,  10,  2,  6,  5,  0,  6,  3]

^   若当前元素 >= maxHeap.peek() , 扔到minHeap里去,minHeap会自动将内部最小值sort到peek位置

[6,  10,  2,  6,  5,  0,  6,  3]

^   当前元素 < maxHeap.peek() , 扔到maxHeap里去

此时maxHeap.size() - minHeap.size()  = 2 需要维护平衡

......

如此以往,直至扫完整个数据。

代码:

 class MedianFinder {

     /** initialize your data structure here. */
private PriorityQueue<Integer> _maxHeap;
private PriorityQueue<Integer> _minHeap; public MedianFinder() {
_maxHeap = new PriorityQueue<> ((o1,o2) -> o2-o1);
_minHeap = new PriorityQueue<> ((o1,o2) -> o1-o2);
} public void addNum(int num) {
// put each integer into either maxHeap or minHeap
if(_maxHeap.isEmpty() || num < _maxHeap.peek()){
_maxHeap.add(num);
} else{
_minHeap.add(num);
}
// keep balance
if(_maxHeap.size() ==_minHeap.size()+2){
_minHeap.add(_maxHeap.poll());
} if(_minHeap.size() ==_maxHeap.size()+1){
_maxHeap.add(_minHeap.poll());
} }
// the number of data is even or odd
public double findMedian() {
if (_maxHeap.size() == _minHeap.size()) {
return (_maxHeap.peek() + _minHeap.peek()) / 2.0;
}else {
return _maxHeap.peek();
}
}
} /**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/

[leetcode]295. Find Median from Data Stream数据流的中位数的更多相关文章

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

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

  2. 295 Find Median from Data Stream 数据流的中位数

    中位数是排序后列表的中间值.如果列表的大小是偶数,则没有中间值,此时中位数是中间两个数的平均值.示例:[2,3,4] , 中位数是 3[2,3], 中位数是 (2 + 3) / 2 = 2.5设计一个 ...

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

  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

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

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

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

  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. tensorflow定义神经网络损失函数MSE

    import numpy as np import tensorflow as tf y_pred = np.array([[1], [2], [3]],dtype=np.float32) y_rea ...

  2. 第4章 文件和目录(5)_贯穿案例2:mini shell(1)

    6. 贯穿案例2:mini shell(1) [阶段性任务]实现cd.pwd和quit命令 //job.h #ifndef __JOB_H__ #define __JOB_H__ //接收命令行参数 ...

  3. 常用数据库4 mongodb

    知识内容: 1.mongodb介绍与基本使用 2.mongodb操作 一.mongodb介绍与基本使用 1.mongodb介绍 Mongodb是一款强大,灵活,且易于扩展的通用型数据库.它能扩展出非常 ...

  4. apache伪静态失败,但是phpinfo显示有rewrite的时候考虑的情况

    大家知道除了加载loadmodule后 还需要修改http.conf 使apache支持.htaccess 允许在任何目录中使用“.htaccess”文件,将“AllowOverride”改成“All ...

  5. HTML5 借助http请求发送formdata对象,从而上传文件 XMLHttpRequest, FormData

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  6. leetcode929

    package main import ( "fmt" "strings" ) func numUniqueEmails(emails []string) in ...

  7. socket 网络连接基础

    socket 客户端 import socket 1.client = socket.socket()  # socket.TCP/IP 选择连接的类型,默认为本地连接 2.client.connec ...

  8. Datetime 24小时制

    24小时制: DateTime dt = DateTime.Now; string dt24 = dt.ToString("yyyy-MM-dd HH:mm:ss"); 12小时制 ...

  9. JVM内存管理基础

     JVM 虚拟机架构(图片来源: 浅析Java虚拟机结构与机制) JVM 内存区域 JVM会将Java进程所管理的内存划分为若干不同的数据区域. 这些区域有各自的用途.创建/销毁时间: (图片来源:  ...

  10. 树莓派3用create_ap变身无线AP

    1.git clone https://github.com/oblique/create_ap.git2.cd create_ap3.sudo make install就这样安装好了4.接下来安装依 ...