295 Find Median from Data Stream

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了295 Find Median from Data Stream相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

295. Find Median from Data Stream

295. Find Median from Data Stream

295. Find Median from Data Stream

leetcode295 Find Median from Data Stream

295. Find Median from Data Stream

[leetcode]295. Find Median from Data Stream?????????????????????