Skip to content

Commit 6c9c913

Browse files
authored
Create employee-free-time.cpp
1 parent b929cb9 commit 6c9c913

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

C++/employee-free-time.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(m * logn), m is the number of schedule, n is the number of employees, m >= n
2+
// Space: O(n)
3+
4+
/**
5+
* Definition for an interval.
6+
* struct Interval {
7+
* int start;
8+
* int end;
9+
* Interval() : start(0), end(0) {}
10+
* Interval(int s, int e) : start(s), end(e) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule) {
16+
vector<Interval> result;
17+
using P = pair<int, pair<int, int>>;
18+
priority_queue<P, vector<P>, greater<P>> min_heap;
19+
for (int i = 0; i < schedule.size(); ++i) {
20+
min_heap.emplace(schedule[i][0].start, make_pair(i, 0));
21+
}
22+
int last_end = -1;
23+
while (!min_heap.empty()) {
24+
int t;
25+
pair<int, int> p;
26+
tie(t, p) = min_heap.top(); min_heap.pop();
27+
if (0 <= last_end && last_end < t) {
28+
result.emplace_back(last_end, t);
29+
}
30+
last_end = max(last_end, schedule[p.first][p.second].end);
31+
if (p.second + 1 < schedule[p.first].size()) {
32+
min_heap.emplace(schedule[p.first][p.second + 1].start, make_pair(p.first, p.second + 1));
33+
}
34+
}
35+
return result;
36+
}
37+
};

0 commit comments

Comments
 (0)