LeetCode 295. Find Median from Data Stream數據流的中位數 (C++/Java)

題目:

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.html

For example,less

[2,3,4], the median is 3ide

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

Design a data structure that supports the following two operations:spa

  • 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.

 

Example:code

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

分析:

中位數是有序列表中間的數。若是列表長度是偶數,中位數則是中間兩個數的平均值。htm

很明顯咱們最好不要每調用一次求中位數函數就從新計算一遍,這樣作時間複雜度較高。blog

 劍指offer中有一道相同的題目,能夠參考這篇理解這道題,劍指Offer-63.數據流中的中位數(C++/Java)element

程序:

C++get

class MedianFinder { public: /** initialize your data structure here. */ MedianFinder() { index = 0; } void addNum(int num) { if(index % 2 == 0){ minHeap.push(num); maxHeap.push(minHeap.top()); minHeap.pop(); } else{ maxHeap.push(num); minHeap.push(maxHeap.top()); maxHeap.pop(); } index++; } double findMedian() { double res = 0; if(index % 2 == 0){ res = (double)(maxHeap.top() + minHeap.top()) / 2; return res; } else{ res = (double)maxHeap.top(); return res; } } private: priority_queue <int, vector<int>, less<int> > maxHeap; priority_queue <int, vector<int>, greater<int> > minHeap; int index; };

Java

class MedianFinder { /** initialize your data structure here. */
    public MedianFinder() { minHeap = new PriorityQueue<Integer>(); maxHeap = new PriorityQueue<Integer>(11,new Comparator<Integer>(){ @Override public int compare(Integer i1,Integer i2){ return i2-i1; } }); index = 0; } public void addNum(int num) { if(index % 2 == 0){ minHeap.offer(num); maxHeap.offer(minHeap.poll()); } else{ maxHeap.offer(num); minHeap.offer(maxHeap.poll()); } index++; } public double findMedian() { double res = 0; if(index % 2 == 0){ res = (minHeap.peek() + maxHeap.peek()) / 2.0; return res; } else{ res = maxHeap.peek(); return res; } } private PriorityQueue<Integer> minHeap; private PriorityQueue<Integer> maxHeap; private int index; }
相關文章
相關標籤/搜索