Skip to content

Commit d608221

Browse files
authored
Create meeting-scheduler.cpp
1 parent 37c97cd commit d608221

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

C++/meeting-scheduler.cpp

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Time: O(n) ~ O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> minAvailableDuration(vector<vector<int>>& slots1, vector<vector<int>>& slots2, int duration) {
7+
vector<pair<int, int>> min_heap;
8+
for (const auto& slot : slots1) {
9+
if (slot[1] - slot[0] >= duration) {
10+
min_heap.emplace_back(slot[0], slot[1]);
11+
}
12+
}
13+
for (const auto& slot : slots2) {
14+
if (slot[1] - slot[0] >= duration) {
15+
min_heap.emplace_back(slot[0], slot[1]);
16+
}
17+
}
18+
make_heap(min_heap.begin(), min_heap.end(), greater<>()); // Time: O(n)
19+
while (min_heap.size() > 1) {
20+
pop_heap(min_heap.begin(), min_heap.end(), greater<>()); // Time: O(logn)
21+
const auto left = min_heap.back();
22+
min_heap.pop_back();
23+
pop_heap(min_heap.begin(), min_heap.end(), greater<>());
24+
const auto right = min_heap.back();
25+
min_heap.pop_back();
26+
min_heap.emplace_back(right);
27+
push_heap(min_heap.begin(), min_heap.end(), greater<>());
28+
if (left.second - right.first >= duration) {
29+
return {right.first, right.first + duration};
30+
}
31+
}
32+
return {};
33+
}
34+
};
35+
36+
// Time: O(nlogn)
37+
// Space: O(n)
38+
class Solution2 {
39+
public:
40+
vector<int> minAvailableDuration(vector<vector<int>>& slots1, vector<vector<int>>& slots2, int duration) {
41+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap;
42+
for (const auto& slot : slots1) {
43+
if (slot[1] - slot[0] >= duration) {
44+
min_heap.emplace(slot[0], slot[1]);
45+
}
46+
}
47+
for (const auto& slot : slots2) {
48+
if (slot[1] - slot[0] >= duration) {
49+
min_heap.emplace(slot[0], slot[1]);
50+
}
51+
}
52+
while (min_heap.size() > 1) {
53+
const auto left = min_heap.top();
54+
min_heap.pop();
55+
const auto right = min_heap.top();
56+
if (left.second - right.first >= duration) {
57+
return {right.first, right.first + duration};
58+
}
59+
}
60+
return {};
61+
}
62+
};
63+
64+
// Time: O(nlogn)
65+
// Space: O(n)
66+
class Solution3 {
67+
public:
68+
vector<int> minAvailableDuration(vector<vector<int>>& slots1, vector<vector<int>>& slots2, int duration) {
69+
sort(slots1.begin(), slots1.end());
70+
sort(slots2.begin(), slots2.end());
71+
int i = 0, j = 0;
72+
while (i < slots1.size() && j < slots2.size()) {
73+
const auto& left = max(slots1[i][0], slots2[j][0]);
74+
const auto& right = min(slots1[i][1], slots2[j][1]);
75+
if (left + duration <= right) {
76+
return {left, left + duration};
77+
}
78+
if (slots1[i][1] < slots2[j][1]) {
79+
++i;
80+
} else {
81+
++j;
82+
}
83+
}
84+
return {};
85+
}
86+
};

0 commit comments

Comments
 (0)