读取数据流的中位数

利用一个大根堆和一个小根堆,中位数始终位于堆顶或是两个堆顶的平均数。

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

public class Solution {
    int count = 0;
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //小根堆
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(11, new Comparator<Integer>(){ //大根堆
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    
    public void Insert(Integer num) {
        if(count % 2 == 0) { //已有偶数个数据,数据加小根堆
            maxHeap.offer(num); //先插进大根堆
            minHeap.offer(maxHeap.poll());//再从大根堆中把最大的插进小根堆
        } else { //奇数个,插大根堆
            minHeap.offer(num);
            maxHeap.offer(minHeap.poll());
        }
        count++;
    }

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

猜你喜欢

转载自blog.csdn.net/tjgongxl/article/details/89648346
今日推荐