天天看點

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

給出一串數字流水,要求求出他的中位數

中位數就是一串已排序數組中中間位置的數字,偶數長度取和除2,

是以使用兩個隊列,一個儲存前半段的隊列,一個儲存後半段的隊列,

儲存前半段的是極大堆,儲存後半段的是極小堆,每次取堆頂元素可以保證就是中位數

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

public class MedianFinder {

    // Adds a number into the data structure.
    PriorityQueue<Long> maxHeap = new PriorityQueue<>(new Comparator<Long>() {
        public int compare(Long o1, Long o2) {
            long o = o2 - o1;
            return (int) o;
        }
    });
    PriorityQueue<Long> minHeap = new PriorityQueue<>(new Comparator<Long>() {
        public int compare(Long o1, Long o2) {
            long o = o1 - o2;
            return (int) o;
        }
    });

    public void addNum(int num) {
        maxHeap.add(num + L);
        minHeap.add(maxHeap.poll());
        if(minHeap.size() - maxHeap.size() > ){
            maxHeap.add(minHeap.poll());
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        return minHeap.size() > maxHeap.size() ? minHeap.peek() : (minHeap.peek() + maxHeap.peek()) / ;
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> q = new PriorityQueue<>(new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                int o = o1 - o2;
                return o;
            }
        });
        q.add();
        q.add();
        q.add();
        System.out.println(q.poll());

        MedianFinder m = new MedianFinder();
        m.addNum();
        System.out.println(m.findMedian());
        m.addNum();
        System.out.println(m.findMedian());
        m.addNum();
        System.out.println(m.findMedian());
        m.addNum(-);
        System.out.println(m.findMedian());
        m.addNum(-);
        System.out.println(m.findMedian());
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();