题解 | 售价的中位数

售价的中位数

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

  1. 大小顶堆的用法
  2. https://blog.csdn.net/qq_41845823/article/details/124281687

import java.util.*;


public class Solution {

    public double[] findMedianPrice (int[] prices) {
        PriorityQueue<Integer> l = new PriorityQueue<>((o1, o2) -> o2 - o1);
        PriorityQueue<Integer> r = new PriorityQueue<>();
        final int n = prices.length;
        double[] ans = new double[n];
        for (int i = 0; i < n; ++i) {
            l.add(prices[i]);
            if(!r.isEmpty() && l.peek() > r.peek()) {
                final int t1 = l.poll();
                final int t2 = r.poll();
                l.add(t2);
                r.add(t1);
            }
            if (l.size() - r.size() == 2) {
                r.add(l.poll());
            }
            if ((i & 1) == 1) {
                ans[i]= 0.5d * (l.peek() + r.peek());
            } else {
                ans[i] = 1d * l.peek();
            }
        }
        return ans;
    }
}

全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
秋招吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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