Advertisement
Guest User

Untitled

a guest
Jul 31st, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. public class MedianFinder {
  2.    
  3.     // elements higher than the median go into this queue... but
  4.     PriorityQueue<Integer> _maxQueue = new PriorityQueue<Integer>(10, new Comparator<Integer>() {
  5.            
  6.             @Override
  7.             public int compare(Integer a, Integer b) {
  8.                 return a - b;
  9.             }
  10.            
  11.         });
  12.     PriorityQueue<Integer> _minQueue = new PriorityQueue<Integer>(10, new Comparator<Integer>() {
  13.            
  14.             @Override
  15.             public int compare(Integer a, Integer b) {
  16.                 return b - a;
  17.             }
  18.            
  19.         });
  20.    
  21.  
  22.     // Adds a number into the data structure.
  23.     public void addNum(int num) {
  24.         if (_maxQueue.isEmpty() && _minQueue.isEmpty()) {
  25.             _minQueue.offer(num);
  26.             return;
  27.         }
  28.        
  29.         double currMedian = findMedian();
  30.        
  31.         if ((double)num > currMedian) {
  32.             if (_maxQueue.size() > _minQueue.size()) {
  33.                 _minQueue.offer(_maxQueue.poll());
  34.             }
  35.            
  36.             _maxQueue.offer(num);
  37.         } else {
  38.             if (_minQueue.size() > _maxQueue.size()) {
  39.                 _maxQueue.offer(_minQueue.poll());
  40.             }
  41.            
  42.             _minQueue.offer(num);
  43.         }
  44.     }
  45.  
  46.     // Returns the median of current data stream
  47.     public double findMedian() {
  48.         if (_maxQueue.isEmpty()) {
  49.             return (double)_minQueue.peek();
  50.         } else if (_minQueue.isEmpty()) {
  51.             return (double)_maxQueue.peek();
  52.         } else {
  53.             if ((_maxQueue.size() + _minQueue.size()) % 2 == 0) {
  54.                 return (double)(_maxQueue.peek() + _minQueue.peek()) / 2;
  55.             }
  56.             return _maxQueue.size() > _minQueue.size() ? _maxQueue.peek() : _minQueue.peek();
  57.         }
  58.     }
  59. };
  60.  
  61. // Your MedianFinder object will be instantiated and called as such:
  62. // MedianFinder mf = new MedianFinder();
  63. // mf.addNum(1);
  64. // mf.findMedian();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement