295. 数据流的中位数

复制代码
295. 数据流的中位数
中位数是有序整数列表中的中间值。如果列表的大小是偶数,则没有中间值,中位数是两个中间值的平均值。

例如 arr = [2,3,4] 的中位数是 3 。
例如 arr = [2,3] 的中位数是 (2 + 3) / 2 = 2.5 。
实现 MedianFinder 类:

MedianFinder() 初始化 MedianFinder 对象。

void addNum(int num) 将数据流中的整数 num 添加到数据结构中。

double findMedian() 返回到目前为止所有元素的中位数。与实际答案相差 10-5 以内的答案将被接受。

list 存储 超时

java 复制代码
class MedianFinder {

    List<Integer> list = new ArrayList<>();

    public MedianFinder() {

    }
    
    public void addNum(int num) {
        int i = list.size();
        while (i > 0) {
            if (num < list.get(i-1)) {
                i-=1;
            } else {
                break;
            }
        }
        if (i == list.size()) {
            list.add(num);
        } else {
            list.add(i, num);
        }
    }
    
    public double findMedian() {
        int l = list.size();
        if (l % 2 == 1) {
            return list.get(l/2);
        }
        return (list.get(l/2) + list.get(l/2-1)) / 2.0D;
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */

最大最小堆

java 复制代码
class MedianFinder {

    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>((a, b) -> b-a);
    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>((a, b) -> a-b);

    public MedianFinder() {

    }
    
    public void addNum(int num) {
        if (maxHeap.isEmpty() || num < maxHeap.peek()) {
            maxHeap.offer(num);
            if (minHeap.size() + 1 < maxHeap.size()){
                minHeap.offer(maxHeap.poll());
            }
        }  else {
            minHeap.offer(num);
            if (minHeap.size() > maxHeap.size()) {
                maxHeap.offer(minHeap.poll());
            }
        }
    }
    
    public double findMedian() {
        if (maxHeap.size() > minHeap.size()) {
            return maxHeap.peek();
        }
        return (minHeap.peek() + maxHeap.peek()) / 2.0D;
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
相关推荐
文丑颜不良啊10 分钟前
LeetCode851~875题目解析
java·leetcode
技术老孙11 分钟前
给 Agent 装上对话框 —— AgentScope-Java 接入 Spring Boot 与 SSE 流式实战
java·开发语言·spring boot
Navigator_Z24 分钟前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
指剑1 小时前
亚麻云之EC2——安全组与密钥对:SSH 端口怎么开才安全,Permission denied (publickey) 和连接超时排查
java·安全·ssh
_Evan_Yao8 小时前
Redis 缓存穿透、击穿、雪崩,一次讲清!
java·spring·mybatis
梓豪csd9 小时前
消息订阅中心:谁该收到哪条通知
java·开发语言·人工智能·低代码·自动化·1024程序员节
秋饼9 小时前
Spring AI 2.1 Message Parts 深度实战:推理签名回放与跨轮记忆持久化的源码级落地
java·ai·技术分享·后端开发
thefool11226610 小时前
TCP 1
java·1024程序员节
金銀銅鐵12 小时前
[Java] 用 GUI 展示 EnumSet 增减元素时的内部变化(下)
java·后端·ai编程
?abc!12 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode