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 设计数据结构存储数据流并能找出数据流的中位数。
思路:首先找中位数是需要对数据流进行排序的。但是这里不是一次给出所有数据,而是逐渐累加。因此要维护一个有序数列。
首先想到的是Java中的SortedSet可以维护有序集,但是在获取中位数的时候必须要转换成数组,才能直接获取到中位数,时间复杂度较大。超时。
class MedianFinder {

    private int count;
private int sum;
private java.util.SortedSet<Integer> set; public MedianFinder() {
set = new TreeSet();
} // Adds a number into the data structure.
public void addNum(int num) {
set.add(num);
} // Returns the median of current data stream
public double findMedian() {
Integer[] list = set.toArray(new Integer[0]);
int size = set.size();
double res = 0.0;
if(size % 2 == 0) {
res = (double)(list[size/2] + list[size/2 - 1]) / 2.0;
}
else {
res = (double)list[size/2];
}
return res;
}
}; // Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

然后看到网上有用优先队列实现的,思路是这样的,维护两个优先队列,其实内部是用堆实现的。维护一个大顶堆,一个小顶堆。分别存储数据流中较大的一般和较小的一半。如果数据流的总数是奇数那么大顶堆中的个数要多一个,这样一来在获取中位数的时候,对于数据流总数是奇数的情况直接返回大顶堆堆顶,对于数据流总数是偶数的情况返回两个堆顶的平均数。最重要的是要维护两个堆的大小。在优先队列中offer,poll时间复杂度为O(logn) peek时间复杂度为O(1),所以addNum的时间复杂度为O(logn),findMedian时间复杂度为O(1)。

public class MedianFinder {

    private Queue<Integer> maxHeap; //大顶堆
private Queue<Integer> minHeap; //小顶堆 public MedianFinder() {
maxHeap = new PriorityQueue<Integer>(11,Collections.reverseOrder());
minHeap = new PriorityQueue<Integer>();
} public void addNum(int num) {
//插入大顶堆
if(maxHeap.size()==0 || maxHeap.peek()>=num) {
maxHeap.offer(num);
if(maxHeap.size()-1 > minHeap.size()) {
minHeap.offer(maxHeap.poll());
}
}
//插入小顶堆
else if(minHeap.size()==0 || minHeap.peek() < num) {
minHeap.offer(num);
if(minHeap.size() > maxHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
//两者之间,先考虑大顶堆。
else {
if(maxHeap.size() <= minHeap.size()) {
maxHeap.offer(num);
}
else {
minHeap.offer(num);
}
} } public double findMedian() {
if(maxHeap.size() == minHeap.size()) {
return (double)(maxHeap.peek() + minHeap.peek()) / 2.0;
}
else {
return (double)maxHeap.peek();
}
} }


LeetCode——Find Median from Data Stream的更多相关文章

  1. [LeetCode] Find Median from Data Stream

    Find Median from Data Stream Median is the middle value in an ordered integer list. If the size of t ...

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

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

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

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

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

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

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

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

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

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

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

  9. LeetCode OJ: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. HOWTO - Basic MSI安装包在安装运行过程中如何获取完整源路径

    有朋友问到如何在一个Windows Installer安装包中获取安装包源路径,就是在安装包运行过程中动态获取*.msi所在完整路径. 这个问题分两类,如果我们的安装包只是一个*.msi安装文件,那么 ...

  2. Js 数据容量单位转换(kb,mb,gb,tb)

    function bytesToSize(bytes) { if (bytes === 0) return '0 B'; var k = 1000, // or 1024 sizes = ['B', ...

  3. js 去掉字符串前面的0

    <script>var a='00123';alert(a.replace(/\b(0+)/gi,""));</script>

  4. C#数据库绑定

    .Net对数据库的绑定 using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...

  5. 面包板入门电子制作(class1)视频 全套30集高清

    面包板入门电子制作(class1)套件(30集高清) 本套件以电子制作中最基础的元器件在面包板上搭建电路,用启发性的视频教学方式,使学习者熟悉电子电路基础.发挥想像力.在创新设计和制作中学会独立设计和 ...

  6. JS 获取自定义标签

    <abc-aaa xwe='sdf'>AAAAAAAAAAAAAAAAAAAAAA</abc-aaa> alert($("abc-aaa").attr(&q ...

  7. android 虚线

    <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http: ...

  8. 清除mac os svn密码命令行缓存

    删除认证缓存设置即可,如下:rm -rf ~/.subversion/auth by yytong

  9. HPUX 大文件系统扩容

    1.比对出新增加的磁盘 ioscan -fnuC disk    ioscan -m dsf         ioscan -fnC disk ioscan -m dsf 2.创建物理卷 pvcrea ...

  10. [GraphQL] Create a GraphQL Schema

    we’ll take a look at the GraphQL Language and write out our first GraphQL Schema. We’ll use the grap ...