题解 | #售价的中位数#

售价的中位数

https://www.nowcoder.com/practice/a1c7e3a0b2fa46da8a3430617b7d74ca

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param prices int整型一维数组
     * @return double浮点型一维数组
     */
    public double[] findMedianPrice (int[] prices) {
        // write code here
        List<Double> res = new ArrayList<>();
        PriorityQueue<Integer> r = new PriorityQueue<>();
        PriorityQueue<Integer> l = new PriorityQueue<>((a, b) -> b - a);
        int n = prices.length;
        for (int i = 0; i < n; i++) {
            l.add(prices[i]);
            if (!r.isEmpty() && l.peek() > r.peek()) {
                int t1 = l.poll();
                int t2 = r.poll();
                l.add(t2);
                r.add(t1);
            }
            if (l.size() - r.size() == 2) {
                r.add(l.poll());
            }
            if ((i & 1) == 1) {
                res.add(0.5 * (l.peek() + r.peek()));
            } else {
                res.add(1.0 * l.peek());
            }
        }

        double[] result = new double[res.size()];
        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        return result;
    }
}

该段代码使用的编程语言是Java。

这段代码是一个解决中位数价格问题的解决方案。给定一个整型向量prices,函数findMedianPrice会返回一个浮点型向量,其中包含了每次插入价格后的中位数。该问题通过维护两个堆来解决,一个最大堆l和一个最小堆r

全部评论

相关推荐

豆泥🍀:同26届,加油,我也还没找到查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务