253. Meeting Rooms II
Problem description:
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:1
2Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:1
2Input: [[7,10],[2,4]]
Output: 1
Solution:
The idea of solving this question is: whenever there is a start meeting, we need to add one room.
for example, we have meetings that span along time as follows:1
2
3
4|_____|
|______|
|________|
|_______|
Then, the start time array and end time array after sorting appear like follows:
1 | || || |
We can use a map to store all the position that have start
or end
. If there’s a start
, we increase 1
on that position, means that we need a conference room. On the other hand, we decrease 1
on end
, denotes that we finish using a meeting room.
Then we can use a variable to store current
using meeting room, and another variable to store the peak
of using meeting rooms.
1 | /** |
time complexity: $O(nlogn)$, map use $O(logn)$ for insertion, and n elements.
space complexity: $O(n)$
Solution 2 Heap
Thought process, always a good idea to sort meeting start time. When we go through each meeting, we want to find the earliest ended
meeting so we can put another meeting after it.
We could then use a min heap
to store the end time. When we see another interval.start
≥ heap.peek()
, we know there’s a meeting already ended when interval
meeting starts. So we can schedule the meeting after that.
1 | class Solution: |
1 | Example |