Java - 2 PriorityQueue solution


  • 0
    D
    public class MedianFinder {
        
        public class MaxHeapComparator implements Comparator<Integer> {
            
            public int compare(Integer i1, Integer i2) {
                return i2 - i1;
            }
            
        }
        
        PriorityQueue<Integer> leftMaxHeap;
        PriorityQueue<Integer> rightMinHeap;
        
        public MedianFinder() {
            //left is a max heap
            this.leftMaxHeap = new PriorityQueue<Integer>(new MaxHeapComparator());
            this.rightMinHeap = new PriorityQueue<Integer>();
        }
    
        // Adds a number into the data structure.
        public void addNum(int num) {
            leftMaxHeap.add(num);
            if (leftMaxHeap.size() > rightMinHeap.size() + 1) {
                int topOfLeft = leftMaxHeap.poll();
                rightMinHeap.add(topOfLeft);
            }
            if (rightMinHeap.size() > 0 && (rightMinHeap.peek() < leftMaxHeap.peek())) {
                //do a swap
                int left = leftMaxHeap.poll();
                int right = rightMinHeap.poll();
                leftMaxHeap.add(right);
                rightMinHeap.add(left);
            }
        }
    
        // Returns the median of current data stream
        public double findMedian() {
            if (leftMaxHeap.size() == 0) return (double) 0;
            
            if ((leftMaxHeap.size() + rightMinHeap.size()) % 2 == 0) {
                return (double) (leftMaxHeap.peek() + rightMinHeap.peek()) / 2;
            } else {
                return (double) leftMaxHeap.peek();
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.