[AlgoExpert] Continuous Median

Continuous Median

  • Time : O(logn) for insert O(1) for getMedian
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using namespace std;

// Do not edit the class below except for
// the insert method. Feel free to add new
// properties and methods to the class.
class ContinuousMedianHandler {
public:
priority_queue<int> less;
priority_queue<int, vector<int>, greater<int>> greater;

void insert(int number) {
greater.push(number);
while(greater.size() > less.size()) {
less.push(greater.top());
greater.pop();
}
}

double getMedian() {
if(less.empty()) return -1.0;
if(greater.size() == less.size()) {
return (greater.top() + less.top()) / 2.0;
}
return less.top();
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/11/PS/AlgoExpert/continuous-median/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.