美文网首页
295. Find Median from Data Strea

295. Find Median from Data Strea

作者: Super_Alan | 来源:发表于2018-05-02 13:22 被阅读0次

    LeetCode Link

    class MedianFinder {
        private PriorityQueue<Integer> smallMaxHeap = null;
        private PriorityQueue<Integer> bigMinHeap = null;
        
        public MedianFinder() {
            smallMaxHeap = new PriorityQueue<Integer>(10, Collections.reverseOrder());
            bigMinHeap = new PriorityQueue<Integer>(10);
        }
        
        // keep smallMaxHeap.size euqal to (bigMinHeap.size or bigMinHeap.size + 1) 
        public void addNum(int num) {
            if (smallMaxHeap.isEmpty() || num < smallMaxHeap.peek()) {
                smallMaxHeap.offer(num);
                if (smallMaxHeap.size() == bigMinHeap.size() + 2) {
                    bigMinHeap.offer(smallMaxHeap.poll());
                }
            } else {
                bigMinHeap.offer(num);
                if (bigMinHeap.size() > smallMaxHeap.size()) {
                    smallMaxHeap.offer(bigMinHeap.poll());
                }
            }
        }
        
        public double findMedian() {
            if (smallMaxHeap.isEmpty()) {
                return 0.0;
            } else if (smallMaxHeap.size() == bigMinHeap.size()) {
                return (smallMaxHeap.peek() + bigMinHeap.peek()) / 2.0;
            }
            
            return (double)smallMaxHeap.peek();
        }
    }
    

    相关文章

      网友评论

          本文标题:295. Find Median from Data Strea

          本文链接:https://www.haomeiwen.com/subject/oixcrftx.html