数据流中的中位数(java版)

来源:互联网 发布:qsfp28光模块端口 编辑:程序博客网 时间:2024/06/13 08:15

【题目描述】如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。


【解题思路】
//1. 声明一个List,存储每次读入的字符
//2. 求当前list中的中位数

import java.util.ArrayList;import java.util.Arrays;public class Solution {    private ArrayList<Integer> arr = new ArrayList<Integer>();    //读入字符    public void Insert(Integer num) {        arr.add(num);    }    //求中位数    public Double GetMedian() {        double middle = 0;        int size = arr.size();        if(size != 0){            Integer[] array = (Integer[])arr.toArray(new Integer[size]);            Arrays.sort(array);            if(size%2 == 0){                middle = (array[size/2-1]+array[size/2])/2.0;            }else{                int inx = size/2;                middle = array[inx];            }        }        return middle;    }}

【解题思路2】
//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. 具体的实施方案。当数据总数为偶数时,新加入的元素,应当进入小根堆,注意不是直接进入小根堆,而是经大根堆筛选后取大根堆中最大元素进入小根堆;当数据总数为奇数时,新加入的元素,应当进入大根堆。注意不是直接进入大根堆,而是经小根堆筛选后取小根堆中最大元素进入大根堆。