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

    思路:
    采用堆,一个大根堆,一个小根堆。(小根堆存放偏大得数,大根堆存放偏小的数)
    第一个数先读到大根堆中,
    后面的数,对比大根堆堆顶,如果小于等于堆顶放入大根堆,
    否则尝试放入小根堆,如果小根堆空,放入,否者对比小根堆堆顶,大于堆顶放入小根堆。否则放入大根堆。
    如果两个堆个数相差>1;取出数量多的堆顶,放到数目少的里面。

    1. public static class MedianHolder{
    2. PriorityQueue<Integer> minHeap;
    3. PriorityQueue<Integer> maxHeap;
    4. public MedianHolder(){
    5. this.minHeap = new PriorityQueue<>();
    6. this.maxHeap = new PriorityQueue<>(new MaxHeapComparator());
    7. }
    8. public void modify() {
    9. int count = maxHeap.size() - minHeap.size();
    10. if (Math.abs(count) >1) {
    11. if(count >0) {
    12. minHeap.add(maxHeap.poll());
    13. }else {
    14. maxHeap.add(minHeap.poll());
    15. }
    16. }
    17. }
    18. //naive!!!!!要考虑全面!!为空呢?
    19. public void add (int num) {
    20. if(maxHeap.isEmpty()) {
    21. maxHeap.add(num);
    22. return ;
    23. }
    24. if(num <= maxHeap.peek()) {//注意这里是小于大根堆堆顶
    25. maxHeap.add(num);
    26. }else {//否者尝试放入小根堆,尝试!!!尝试!!!
    27. if(minHeap.isEmpty()) {
    28. minHeap.add(num);
    29. return ;
    30. }
    31. if(num >= minHeap.peek()) {
    32. minHeap.add(num);
    33. }else {
    34. maxHeap.add(num);
    35. }
    36. }
    37. modify();
    38. }
    39. public Integer getMedian() {
    40. int maxHeapSize = maxHeap.size();
    41. int minHeapSize = minHeap.size();
    42. if (maxHeap.isEmpty() && minHeap.isEmpty()) {
    43. return null;
    44. }
    45. Integer maxHeapHead = maxHeap.peek();
    46. Integer minHeadHead = minHeap.peek();
    47. if(((maxHeapSize + minHeapSize) & 1) == 0){
    48. return (maxHeapHead + minHeadHead)/2;
    49. }
    50. return minHeapSize > maxHeapSize ? minHeadHead :maxHeapHead;
    51. }
    52. }
    53. public static class MaxHeapComparator implements Comparator<Integer>{
    54. @Override
    55. public int compare(Integer o1, Integer o2) {
    56. // TODO Auto-generated method stub
    57. return o2 -o1;
    58. }
    59. }