0
点赞
收藏
分享

微信扫一扫

数据流的中位数

笙烛 2021-09-21 阅读 72
今日算法
题目描述:
示例:
题目分析:
  1. 返回有序元素列表的中位数
    • 如果有序元素列表为奇数,则返回中间位置的元素
    • 如果有序元素列表为偶数,则返回中间两个元素之和再除以2的值
思路:
代码实现:
class MedianFinder {

    // 大顶堆
    PriorityQueue<Integer> left = new PriorityQueue<>((a, b) -> b-a);
    // 小顶堆
    PriorityQueue<Integer> right = new PriorityQueue<>((a, b) -> a-b);

    /** initialize your data structure here. */
    public MedianFinder() {

    }
    
    public void addNum(int num) {
        int leftLen = left.size();
        int rightLen = right.size();
        if (leftLen == rightLen) {
            if (right.isEmpty() || num <= right.peek()) {
                left.add(num);
            } else {
                left.add(right.poll());
                right.add(num);
            }
        } else {
            if (left.peek() <= num) {
                right.add(num);
            } else {
                right.add(left.poll());
                left.add(num);
            }
        }
    }
    
    public double findMedian() {
        int leftLen = left.size();
        int rightLen = right.size();
        if (leftLen == rightLen) {
            return (left.peek() + right.peek()) / 2.0;
        } else {
            return left.peek();
        }
    }
}
举报

相关推荐

0 条评论