-
Notifications
You must be signed in to change notification settings - Fork 0
/
200720-2.cpp
47 lines (43 loc) · 907 Bytes
/
200720-2.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode-cn.com/problems/find-median-from-data-stream/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
auto it = lower_bound(a.begin(), a.end(), num);
a.insert(it, num);
}
double findMedian() {
int n = a.size();
if (n % 2 == 0) {
return (a[n / 2 - 1] + a[n / 2]) / 2.0;
} else {
return a[n / 2];
}
}
private:
vector<int> a;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
int main()
{
{
MedianFinder m;
m.addNum(1);
m.addNum(2);
cout << m.findMedian() << endl; // answer: 1.5
m.addNum(3);
cout << m.findMedian() << endl; // answer: 2
}
return 0;
}