-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_16.10_maxAliveYear.cc
62 lines (59 loc) · 1.33 KB
/
Problem_16.10_maxAliveYear.cc
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
#include <algorithm>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
class Solution
{
public:
// 差分
int maxAliveYear(vector<int>& birth, vector<int>& death)
{
vector<int> diff(2002);
int n = birth.size();
for (int i = 0; i < n; i++)
{
diff[birth[i]]++;
diff[death[i] + 1]--;
}
int max = 0;
int idx = 0;
int sum = 0;
for (int i = 1900; i <= 2000; i++)
{
sum += diff[i];
if (max < sum)
{
max = sum;
idx = i;
}
}
return idx;
}
// 优先级队列
int maxAliveYear2(vector<int>& birth, vector<int>& death)
{
int n = birth.size();
vector<int> idx(n);
for (int i = 0; i < n; i++)
{
idx[i] = i;
}
// 根据开始时间排序
std::sort(idx.begin(), idx.end(), [&](int i, int j) { return birth[i] < birth[j]; });
priority_queue<int, vector<int>, greater<int>> q;
int ans = 0;
for (int i = 0; i < n; i++)
{
// 注意这里不能取等号 death[q.top()] <= birth[idx[i]]
// 题设生于 1908 年、死于 1909 年的人应当被列入 1908 年和 1909 年的计数
while (!q.empty() && death[q.top()] < birth[idx[i]])
{
q.pop();
}
ans = std::max(ans, (int) q.size());
q.push(death[idx[i]]);
}
return ans;
}
};