-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
62 lines (57 loc) · 1.45 KB
/
solution.h
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Code generated by https://github.com/goodstudyqaq/leetcode-local-tester
*/
#if __has_include("../utils/cpp/help.hpp")
#include "../utils/cpp/help.hpp"
#elif __has_include("../../utils/cpp/help.hpp")
#include "../../utils/cpp/help.hpp"
#else
#define debug(...) 42
#endif
typedef pair<int, int> pii;
class MedianFinder {
public:
set<pii> S;
set<pii>::iterator it1, it2;
int time;
MedianFinder() {
time = 0;
}
void addNum(int num) {
S.insert({num, time++});
if (S.size() == 1) {
it1 = S.begin();
it2 = S.begin();
} else {
if (S.size() % 2 == 1) {
auto left = *it1, right = *it2;
if (num < left.first) {
it2--;
} else if (num >= right.first) {
it1++;
} else {
it1++;
it2--;
}
} else {
int v = (*it1).first;
if (num < v) {
it1--;
} else if (num >= v) {
it2++;
}
}
}
debug(S, *it1, *it2);
}
double findMedian() {
debug("find");
return 1.0 * (it1->first + it2->first) / 2.0;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/