File tree Expand file tree Collapse file tree 1 file changed +11
-14
lines changed
solution/0200-0299/0295.Find Median from Data Stream Expand file tree Collapse file tree 1 file changed +11
-14
lines changed Original file line number Diff line number Diff line change 1
1
class MedianFinder {
2
2
public:
3
- /* * initialize your data structure here. */
4
3
MedianFinder () {
5
4
}
6
5
7
6
void addNum (int num) {
8
- q1.push (num);
9
- q2.push (q1.top ());
10
- q1.pop ();
11
- if (q2.size () - q1.size () > 1 ) {
12
- q1.push (q2.top ());
13
- q2.pop ();
7
+ maxQ.push (num);
8
+ minQ.push (maxQ.top ());
9
+ maxQ.pop ();
10
+
11
+ if (minQ.size () > maxQ.size () + 1 ) {
12
+ maxQ.push (minQ.top ());
13
+ minQ.pop ();
14
14
}
15
15
}
16
16
17
17
double findMedian () {
18
- if (q2.size () > q1.size ()) {
19
- return q2.top ();
20
- }
21
- return (double ) (q1.top () + q2.top ()) / 2 ;
18
+ return minQ.size () == maxQ.size () ? (minQ.top () + maxQ.top ()) / 2.0 : minQ.top ();
22
19
}
23
20
24
21
private:
25
- priority_queue<int , vector< int >, greater< int >> q1 ;
26
- priority_queue<int > q2 ;
22
+ priority_queue<int > maxQ ;
23
+ priority_queue<int , vector< int >, greater< int >> minQ ;
27
24
};
28
25
29
26
/* *
30
27
* Your MedianFinder object will be instantiated and called as such:
31
28
* MedianFinder* obj = new MedianFinder();
32
29
* obj->addNum(num);
33
30
* double param_2 = obj->findMedian();
34
- */
31
+ */
You can’t perform that action at this time.
0 commit comments