zoukankan      html  css  js  c++  java
  • 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 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
    

    Credits:
    Special thanks to @Louis1992 for adding this problem and creating all test cases.

    Solution:

     1 public class MedianFinder {
     2     // small part, max heap
     3     PriorityQueue<Integer> small = new PriorityQueue<Integer>((a, b) -> (b - a));
     4 
     5     // large part, min heap, contains median if odd number of numbers are added.
     6     PriorityQueue<Integer> large = new PriorityQueue<Integer>();
     7 
     8     // Adds a number into the data structure.
     9     public void addNum(int num) {
    10         if (large.isEmpty()) {
    11             large.add(num);
    12             return;
    13         }
    14 
    15         // total number is even
    16         if (small.size()==large.size()) {
    17             if (num >= small.peek()) {
    18                 // add it to large.
    19                 large.add(num);
    20             } else {
    21                 small.add(num);
    22                 large.add(small.poll());
    23             }
    24         } else {
    25             if (num > large.peek()) {
    26                 large.add(num);
    27                 small.add(large.poll());
    28             } else {
    29                 small.add(num);
    30             }
    31         }
    32     }
    33 
    34     // Returns the median of current data stream
    35     public double findMedian() {
    36         if (small.size()==large.size()){
    37             return (double) (small.peek()+large.peek())/2;
    38         } else {
    39             return (double) large.peek();
    40         }
    41     }
    42 
    43 };
    44 
    45 // Your MedianFinder object will be instantiated and called as such:
    46 // MedianFinder mf = new MedianFinder();
    47 // mf.addNum(1);
    48 // mf.findMedian();
  • 相关阅读:
    MySQL之增_insert-replace
    Linux如何配置bond
    行转列及列转行查询
    SELECT中常用的子查询操作
    SELECT中的多表连接
    MySQL最常用分组聚合函数
    SELECT中的if_case流程函数
    MySQL常用日期时间函数
    MySQL常用数值函数
    dnslog注入
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5828262.html
Copyright © 2011-2022 走看看