Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...]
(si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]] Output: 1
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Notes:
This question is a very popular interview question, since that it can be solved by many methods.
However, this question can be solved by a very intuitive and surprisingly very powerful algorithm: sweeping-line algorithm.
The basic idea is that we just need to sort the start time and end time first. Then scan them from left to right.
1): if we meet with a start time, it means we need to start a new meeting; so meeting room needs +1;
2): if we meet with a end time, it means one meeting is over; so meeting room - 1.
Thus, this question is equivalent to ask: what is the maximum number of meeting that are hold at the same time?
See the code below:
- class Solution {
- public:
- int minMeetingRooms(vector<vector<char>>& intervals) {
- int res = 0;
- vector<pair<int, int>> startEndTimes; //<time, star/end>
- for(auto &a : intervals) {
- startEndTimes.push_back({a[0], 1});//start time
- startEndTimes.push_back({a[0], 0});//end time
- }
- sort(startEndTimes.begin(), startEndTimes.end());
- int count = 0;
- for(auto &a : startEndTimes) {
- if(a.second == 1) ++count;
- else --count;
- res = max(res, count);
- }
- return res;
- }
- };
Similar questions: Given fly-time intervals of planes, what is the maximum number of planes flying at the same time?
No comments:
Post a Comment