Monday, October 7, 2019

Leetcode 253: Meeting Rooms II

https://leetcode.com › problems › meeting-rooms-ii

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:

  1. class Solution {
  2. public:
  3.     int minMeetingRooms(vector<vector<char>>& intervals) {
  4.         int res = 0;
  5.         vector<pair<int, int>> startEndTimes; //<time, star/end>
  6.         for(auto &a : intervals) {
  7.             startEndTimes.push_back({a[0], 1});//start time
  8.             startEndTimes.push_back({a[0], 0});//end time
  9.         }
  10.         sort(startEndTimes.begin(), startEndTimes.end());
  11.         int count = 0;
  12.         for(auto &a : startEndTimes) {
  13.             if(a.second == 1) ++count;
  14.             else --count;
  15.             res = max(res, count);
  16.         }
  17.         return res;
  18.     }
  19. };

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