Advertisement
exmkg

Untitled

Oct 27th, 2024
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. class MedianFinder {
  2.     PriorityQueue<Integer> minHeap = new PriorityQueue<>();
  3.     PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
  4.    
  5.     public MedianFinder() {}
  6.     public void addNum(int num) {
  7.         maxHeap.offer(num);
  8.         minHeap.offer(maxHeap.poll());
  9.  
  10.         if (minHeap.size() > maxHeap.size()) {
  11.             maxHeap.offer(minHeap.poll());
  12.         }
  13.     }
  14.     public double findMedian() {
  15.         if (maxHeap.size() > minHeap.size()) {
  16.             return maxHeap.peek();
  17.         }
  18.         return (minHeap.peek() + maxHeap.peek()) / 2.0d;
  19.     }
  20. }
  21.  
  22. /**
  23.  * Your MedianFinder object will be instantiated and called as such:
  24.  * MedianFinder obj = new MedianFinder();
  25.  * obj.addNum(num);
  26.  * double param_2 = obj.findMedian();
  27.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement