题目:

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

链接: http://leetcode.com/problems/find-median-from-data-stream/

题解:

在Data stream中找到median。这道题是Heap的经典应用,需要同时维护一个最大堆和一个最小堆, 最大堆和最小堆的size <= 当前数字count / 2。在学习heap数据结构的时候一般都会讲到这一题,很经典。

Time Complexity: addNum - O(logn)  , findMedian - O(1),  Space Complexity - O(n)

class MedianFinder {
private PriorityQueue<Integer> maxOrientedHeap;
private PriorityQueue<Integer> minOrientedHeap; public MedianFinder() {
this.minOrientedHeap = new PriorityQueue<Integer>();
this.maxOrientedHeap = new PriorityQueue<Integer>(10, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return i2 - i1;
}
});
}
// Adds a number into the data structure.
public void addNum(int num) {
maxOrientedHeap.add(num); // O(logn)
minOrientedHeap.add(maxOrientedHeap.poll()); // O(logn)
if(maxOrientedHeap.size() < minOrientedHeap.size()) {
maxOrientedHeap.add(minOrientedHeap.poll()); //O(logn)
}
} // Returns the median of current data stream
public double findMedian() { // O(1)
if(maxOrientedHeap.size() == minOrientedHeap.size())
return (maxOrientedHeap.peek() + minOrientedHeap.peek()) / 2.0;
else
return maxOrientedHeap.peek();
}
}; // Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

二刷:

依然使用了两个PriorityQueue,一个maxPQ,一个minPQ。最小堆中存的是较大的一半数据,最大堆中存的是较小的一半数据。当传入数字计数为奇数是,我们直接返回minPQ.peek(), 否则我们返回 (maxPQ.peek() + minPQ.peek()) / 2.0。 这样做速度不是很理想,也许是maxPQ的lambda表达式构建出的comparator没有得到优化,换成普通的comparator速度至少快一倍。也可以用Collections.reverseOrder()来作为maxPQ的comparator。

见到有些朋友用了构建BST来做,这样减少了几次O(logn)的操作,速度会更快,以后在研究。

Java:

Min and Max Heap

Time Complexity: addNum - O(logn)  , findMedian - O(1),  Space Complexity - O(n)

class MedianFinder {
Queue<Integer> minPQ = new PriorityQueue<>();
Queue<Integer> maxPQ = new PriorityQueue<>(10, (Integer i1, Integer i2) -> i2 - i1);
// Adds a number into the data structure.
public void addNum(int num) {
minPQ.offer(num);
maxPQ.offer(minPQ.poll());
if (minPQ.size() < maxPQ.size()) minPQ.offer(maxPQ.poll());
} // Returns the median of current data stream
public double findMedian() {
if (minPQ.size() == maxPQ.size()) return (minPQ.peek() + maxPQ.peek()) / 2.0;
return minPQ.peek();
}
}; // Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

Reference:

https://leetcode.com/discuss/65107/share-my-java-solution-logn-to-insert-o-1-to-query

https://leetcode.com/discuss/64850/short-simple-java-c-python-o-log-n-o-1

https://leetcode.com/discuss/64811/easy-to-understand-double-heap-solution-in-java

https://leetcode.com/discuss/64910/very-short-o-log-n-o-1

https://leetcode.com/discuss/64842/32ms-easy-to-understand-java-solution

https://leetcode.com/discuss/68290/simple-java-solution-with-2-heaps-and-explanation

https://leetcode.com/discuss/64852/java-python-two-heap-solution-o-log-n-add-o-1-find

https://leetcode.com/discuss/94126/18ms-beats-100%25-java-solution-with-bst

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. 剑指offer 最小的k个数 、 leetcode 215. Kth Largest Element in an Array 、295. Find Median from Data Stream(剑指 数据流中位数)

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

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. 了解struts2 action的一些原理

    今天在struts2中的 action方法中,打印了一下当前action,即this,还打印了一下当前action引用的service, 在页面中访问该action方法2次,发现action是不一样的 ...

  2. TWaver初学实战——基于HTML5的交互式地铁图

    每天坐地铁,经常看地铁图,有一天突然想到,地铁图不也是一种拓扑结果吗?TWaver到底能与地铁图擦出怎样的火花呢?   想到就干,先到网上找幅参考图.各种风格的地铁图还挺多,甚至有大学生自主设计制作, ...

  3. android 图片缩放抗锯齿

    之前用的时候只设置了antialias属性,其实要设置两个flag才行 paint.setFlags(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); ...

  4. 一个Linq

    public class CalendaerCollectItem { public int ID { get; set; } public string Name { get; set; } pub ...

  5. Java 7 中 NIO.2 的使用——第四节 文件和目录

    Files类提供了很多方法用于检查在于你真正实际去操作一个文件或目录.这些方法强烈推荐,也非常有用,也能避免很多异常的发生.例如,一个很好的习惯就是在你试着移动一个文件从一个地方到另一个地方的时候,先 ...

  6. xcode 运行报错 Command /usr/bin/codesign failed with exit code 1

           因为更换了证书,导致在运行时报错 Command /usr/bin/codesign failed with exit code 1,查看了网上各种方法,最后发现以下两个值没有同步更新

  7. RobotFramework-调用.py文件

    RobotFramework-调用.py文件,直接运行: 注意:文件路径的\全部换成好了/

  8. 浅谈对git的认识

    在上大二之前我根本不知道git是什么,根本不知道它有什么功能,以及应用于那个领域,那天老师说让我们了解一些它,并对其进行一下学习.我瞬间就蒙了,但是我并没有把其抛在脑后,而是通过在其它方式,对其进行了 ...

  9. Codeforces Round #351 (VK Cup 2016 Round 3, Div. 2 Edition) C - Bear and Colors

    题目链接: http://codeforces.com/contest/673/problem/C 题解: 枚举所有的区间,维护一下每种颜色出现的次数,记录一下出现最多且最小的就可以了. 暴力n*n. ...

  10. FastDFS配置文件(tracker.conf)

    # ===========================基本配置==================================== # 该配置文件是否生效 # false:生效 # true: ...