zoukankan      html  css  js  c++  java
  • 数据流中的中位数

    //1. 使用大顶堆+小顶堆的容器.
    //2. 两个堆中的数据数目差不能超过1,这样可以使中位数只会出现在两个堆的交接处
    //3. 大顶堆的所有数据都小于小顶堆,这样就满足了排序要求。平均数就在两个堆顶的数之中。

    private int count = 0;
    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(15, 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);
            int filteredMaxNum = maxHeap.poll();
            minHeap.offer(filteredMaxNum);
        } else {
            minHeap.offer(num);
            int filteredMinNum = minHeap.poll();
            maxHeap.offer(filteredMinNum);
        }
        count++;
    }
    
    //求中位数
    public Double GetMedian() {
        if (count %2 == 0) {
            return new Double((minHeap.peek() + maxHeap.peek())) / 2;
        } else {
            return new Double(minHeap.peek());
        }
    }

    a. 为了保证两个堆中的数据数目差不能超过1,在Insert()方法中使用了count来辅助实现。
    b. 为了保证小顶堆的元素都小于大顶堆的元素,借用优先队列PriorityQueue。其默认维持队列内升序排列。也可以像上面传入一个比较器,然后使其改变排列顺序。
    c. 具体的实施方案。当数据总数为偶数时,新加入的元素,应当进入小根堆,注意不是直接进入小根堆,而是经大根堆筛选后取大根堆中最大元素进入小根堆;当数据总数为奇数时,新加入的元素,应当进入大根堆。注意不是直接进入大根堆,而是经小根堆筛选后取小根堆中最大元素进入大根堆。

  • 相关阅读:
    jsp标签${fn:contains()}遇到问题记录
    maven更改本地的maven私服
    elk使用记录
    dubbo 报错问题记录:may be version or group mismatch
    mybatis自动生成后无法获取主键id问题
    tomcat关闭异常导致的项目无法重启
    jsp 记录
    spring bean
    JDBC
    el表达式
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/8287270.html
Copyright © 2011-2022 走看看