lc295.java 1.1 KB
Newer Older
L
liu13 已提交
1 2 3
package code;

import java.util.PriorityQueue;
L
liu13 已提交
4 5 6 7 8 9 10 11 12
/*
 * 295. Find Median from Data Stream
 * 题意:流数据中找中位数
 * 难度:Hard
 * 分类:
 * 思路:用两个优先队列,一个保存左半边最大值,一个保存右半边最小值
 *      保持左半边最多比右半边多一个数
 * Tips:
 */
L
liu13 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
public class lc295 {
    class MedianFinder {
        PriorityQueue<Integer> pq1;    //默认是最小,右半边
        PriorityQueue<Integer> pq2;    //左半边

        /** initialize your data structure here. */
        public MedianFinder() {
            this.pq1 = new PriorityQueue();
            this.pq2 = new PriorityQueue();
        }

        public void addNum(int num) {
            pq1.add(num);   //两个队列都过一遍
            pq2.add(-pq1.poll());
            if (pq1.size() < pq2.size())    //如果中位数是一个数,就存在左半边
                pq1.add(-pq2.poll());
        }

        public double findMedian() {
            if(pq1.size()==pq2.size()+1) return pq1.peek();
            return -((double)(-pq1.peek()+pq2.peek()))/2;
        }
    }
}