leetcode学习笔记30

295. Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

For example,
[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
维护两个堆i,一个最小堆,一个最大堆
中间值等于其中一个的堆顶,或者两个堆顶的平均值

class MedianFinder {
	PriorityQueue<Integer> minHeap;
	PriorityQueue<Integer> maxHeap;
    /** initialize your data structure here. */
    public MedianFinder() {
    	minHeap=new PriorityQueue<Integer>(Collections.reverseOrder());
    	maxHeap=new PriorityQueue<Integer>();
    }
   
    public void addNum(int num) {
    	minHeap.add(num);
    	int n=minHeap.poll();
    	maxHeap.offer(n);
    	if(minHeap.size()<maxHeap.size()) {
    		n=maxHeap.poll();
    		minHeap.offer(n);
    	}
    	
    }
    
    
    public double findMedian() {
    	if(minHeap.size()==maxHeap.size()) {
    		return (minHeap.peek()+maxHeap.peek())/2.0;
    	}else {
    		return minHeap.size()>maxHeap.size()?minHeap.peek():maxHeap.peek();
    	}
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38941866/article/details/85238768