码迷,mamicode.com
首页 > 其他好文 > 详细

295 Find Median from Data Stream

时间:2018-08-10 15:49:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:heap   ini   sem   dia   code   return   https   media   rev   

295 Find Median from Data Stream

https://www.youtube.com/watch?v=60xnYZ21Ir0

/////  new PriorityQueue<>(Collections.reverseOrder());

////. smart 
    public void addNum(int num) {
        max.offer(num);
        min.offer(max.poll());
        if (max.size() < min.size()){
            max.offer(min.poll());
        }
    }


/////

class MedianFinder {

    /** initialize your data structure here. */
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
      
    public MedianFinder() {
        
    }
    
    public void addNum(int num) {
      maxHeap.offer(num);
      if(!minHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){
        minHeap.offer(maxHeap.poll());
      }
      if(minHeap.size() > maxHeap.size()){
        maxHeap.offer(minHeap.poll());
      }
      if(maxHeap.size() - minHeap.size() > 1){
        minHeap.offer(maxHeap.poll());
      }
        
    }
    
    public double findMedian() {
      if(maxHeap.size() == minHeap.size()){
        return (maxHeap.peek() + minHeap.peek()) / 2.0 ; /// 2.0 instead of 2 
      }else{
        return maxHeap.peek();
      }
        
    }
}

 

295 Find Median from Data Stream

标签:heap   ini   sem   dia   code   return   https   media   rev   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!