GH1995 / leetcode-test-and-run

方便 leetcode 刷题的小工具
GNU General Public License v2.0
0 stars 0 forks source link

295. Find Median from Data Stream 找出数据流的中位数 #48

Open GH1995 opened 5 years ago

GH1995 commented 5 years ago

295. Find Median from Data Stream

Difficulty: Hard

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:

Example:

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

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

Solution

Language: C++

// #include "leetcode.h"
​
class MedianFinder {
 private:
  priority_queue<int> maxpq;  // 存放较小的一半数字
  priority_queue<int, vector<int>, greater<int>> minpq;  // 存放较大的一半数字
  // maxpq.top() <= minpq.top()
​
 public:
  /** initialize your data structure here. */
  MedianFinder() {}
​
  void addNum(int num) {
    maxpq.push(num);  // 从 maxpq 中移除最大元素并提供给 minpq
    minpq.push(maxpq.top());
    maxpq.pop();
​
    if (maxpq.size() <
        minpq.size()) {  // 如果 minpq 较大,则移除较小元素给 maxpq
      maxpq.push(minpq.top());
      minpq.pop();
    }
  }
​
  double findMedian() {
    if (minpq.size() == maxpq.size())
      return (minpq.top() + maxpq.top()) * 1.0 / 2;
    else
      return maxpq.top();
  }
};
​
/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */
GH1995 commented 5 years ago
  1. maxpq 中移除最大元素并提供给 minpq
  2. 如果 minpq.size() 较大,则移除较小元素给 maxpq