原题
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
解法
最小堆算法. 利用heap[0]永远是队列中最小值这一性质, 我们构建一个heap队列, 遍历intervals, 如果当前的intervals的开始时间在heap[0]之后, 那么两个会议可以用同一个房间, 我们将当前会议的结束时间来替代heap[0]; 否则需要另外开一个房间, 将会议的结束时间加到heap队列里, 最后返回heap的长度.
Time: O(n)
Space: O(1)
代码
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
intervals.sort(key = lambda x: x.start)
heap = []
for i in intervals:
if heap and i.start >= heap[0]:
# two meetings can use the same room
heapq.heapreplace(heap, i.end)
else:
# a new room is allocated
heapq.heappush(heap, i.end)
return len(heap)
会议时间调度算法
本文介绍了一种使用最小堆算法解决会议室调度问题的方法。通过遍历会议时间间隔,判断是否可以复用会议室,实现最小数量的会议室分配。算法时间复杂度为O(n),空间复杂度为O(1)。
6949

被折叠的 条评论
为什么被折叠?



