题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路:

需要求的是中位数,如果我将 1 2 3 4 5 6 7 8定为最终的数据流 此时的中位数是4+5求均值。为什么是4,为什么是5 利用队列我们就可以看得很清楚,4是前半部分最大的值,肯定是维系在大顶堆 而5是后半部分的最小值,肯定是维系在小顶堆。 问题就好理解了: 使用小顶堆存大数据,使用大顶堆存小数据。这样堆顶一取出就是中位数了。 大小顶堆内部默认都是升序排序。

  1. //小顶堆
  2. private PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
  3. //大顶堆
  4. private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(15,new Comparator<Integer>() {
  5. @Override//换成降序排序
  6. public int compare(Integer o1, Integer o2) {
  7. // TODO Auto-generated method stub
  8. return o2-o1;
  9. }
  10. });
  11. int count = 0;
  12. public void Insert(Integer num) {
  13. //当计数为偶数的先压入大顶堆
  14. if(count%2==0) {
  15. maxHeap.offer(num);
  16. int max = maxHeap.poll();
  17. minHeap.offer(max);
  18. }else {
  19. minHeap.offer(num);
  20. int min = minHeap.poll();
  21. maxHeap.offer(min);
  22. }
  23. count++;
  24. }
  25. public Double GetMedian() {
  26. if(count%2==0) {
  27. return new Double((minHeap.peek()+maxHeap.peek())/2);
  28. }else {
  29. return new Double(minHeap.peek());//当为计数为奇数的时候小顶堆会比大顶堆多一个
  30. }
  31. }