Question 1: The minimum meeting room needed
Say we have had a list of meetings with start_time and end_time. For each meeting room, only one meeting can be hold once the meeting starts, and it cannot hold the next meeting until the first one ends. For example, if the first meeting start at 1 and end at 10, then the meeting room can only hold a second meeting starting at or later than 10.
The question is to find the minimum number of meeting rooms needed to hold all the meetings.
Example 1:
meetings = [[2, 5], [4, 6], [5, 9]]
Ans: 2
the first meeting room can hold: [2, 5], [5, 9];
the second meeting room can hold: [4, 6].
Example 2:
meetings = [[1, 10], [2, 3], [3, 7], [4, 6], [5, 8], [6, 9], [7, 11], [10, 12]]
Ans: 4
the first meeting room can hold: [1, 10], [10, 12];
the second meeting room can hold: [2, 3], [3, 7], [7, 11];
the third meeting room can hold: [4, 6], [6, 9];
the fourth meeting room can hold: [5, 8].
Analysis:
As indicated by the second example, we can sort the meeting time based on the starting time. Once we choose the first meeting, then we can search for the next meeting that can be held in the same meeting room. The starting time of the next meeting should be equal to or larger than the ending time of the first meeting.
In this way, we can find a set of meetings that can be held in one meeting room.
But there are other meetings which cannot be held in the same meeting room.
So we need to search the list again, and just repeat the process for the first meeting room, to find all the meetings that can be held in the second meeting room.
To avoid redundancy, we can use a labeling vector to label whether the meeting has been held or not. Or to make sure each meeting be held once.
The time complexity is O(N^2). The initial sorting is O(N^log(N)) which is not the most expensive step.
Is there a faster way?
The answer is yes. For example, using the scanning line algorithm.
The first step is to label the starting and ending times of all meetings. The start time can be 1, the end time can be -1. Then sort all the times increasingly. If the start time equals to end time, then put the end time first.
After this step, we just need to scan through the sorted time list once, to calculate the maximum number of meeting that have overlaps in time. This value is exactly the minimum number of meeting room needed to hold all the meetings on the list.
See the code below:
int minMR(vector<vector<int>>& rs) {
int res = 0, ct = 0;
vector<vector<int>> data;
for(auto &a : rs) {
data.push_back({a[0], 1});
data.push_back({a[1], -1});
}
sort(data.begin(), data.end(), [](vector<int> &a, vector<int> &b) {
if(a[0] == b[0]) return a[1] < b[1];
return a[0] < b[0];
});
for(auto &a : data) {
if(a[1] == 1) ++ct;
else --ct;
res = max(res, ct);
}
return res;
}
Comments
Post a Comment