原题
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
解法
使用优先队列算法, 生成优先队列, 代表已开的房间, 先将时间段按照开始时间排序, 遍历时间段, 如果没有多余的房间, 则将这个会议的加到队列里, 如果有多余的房间且目前会议的起始之间在上个会议的终止时间之后, 更新队列.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
# sort the intervals by start time
intervals.sort(key = lambda x: x.start)
heap = []
for interval in intervals:
if heap and interval.start >= heap[0]:
# room is already used in last meeting and continue to use the same room for this meeting
heapq.heapreplace(heap, interval.end)
else:
heapq.heappush(heap, interval.end)
return len(heap)