The median cattle off the network data stream (large root heap small root heap)

topic:

How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values ​​after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values ​​of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.

Problem solving:

import java.util.Comparator;
import java.util.PriorityQueue;

public  class Solution {
     Private  int COUNT = 0 ;
     Private PriorityQueue <Integer> = minheap new new PriorityQueue <> (); // rootlets stack, store the data stream a large number of vertices in which half of the minimum number
     // large root stack, store the smaller half of the data stream in which the maximum number of vertex number 
    Private PriorityQueue <Integer> = maxheap new new PriorityQueue <Integer> (15, new new Comparator <Integer> () {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });

    public  void the Insert (Integer NUM) {
         IF (COUNT% 2 == 0) { // when the total number of data is an even number, the newly added elements, should the stack into the small root
             // (note that the root is not directly enter the small pile, but after screening large root take large root heap pile element into the small root maximum stack)
             // 1. Add a new element into the first large root stack, the stack screening large root heap largest element 
            maxHeap.offer (NUM);
             int filteredMaxNum = maxheap .poll ();
             // 2. [maximum] elements of large root heap after the screening into the small root heap 
            minHeap.offer (filteredMaxNum);
        } The else { // when the total number of data is an odd number, a new element is added, the stack should enter large root
             // (large root note not directly into the stack, but after screening a small heap take root rootlets maximum heap pile element into the large root)
             // 1. Add a new element into the first small heap root, root by a small heap stack smallest element selected 
            minHeap.offer (NUM);
             int filteredMinNum = minHeap.poll ();
             // 2. after the screening small [ the minimum root stack into the large root stack elemental] 
            maxHeap.offer (filteredMinNum);
        }
        count++;
    }

    public Double GetMedian() {
        if (count %2 == 0) {
            return new Double((minHeap.peek() + maxHeap.peek())) / 2;
        } Else {
             return  new Double (minHeap.peek ());
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/yanhowever/p/12306091.html