Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
#algorithm
#we can use a data structure called priority queue right.
#we need to know when we need a new room and when we can share the room.
# so if the time of two meeting is overlap, we need a new room, the opposite situation we can share the room
# the question is how to definition the overlap. the end time of the current time slot is larger than the begin time of the next time slot, it's overlap, Conversely, do not overlap
# so let's get start it
#We sort the interval time slot by the start time.
#The definition of overlap: the end time of the current time slot is larger than the begin time of the next time slot, [1,11],[10,19], 11 > 10, there is an overlap
#heapq.heapreplace(heap, item)
if not intervals:
return 0
# i'm going to have a heap, free_rooms
free_rooms = []
# and sorted the intervals by the start time
intervals.sort(key = lambda x: x[0])
# so first we push the first end time into the heap to Compare with later start time
heapq.heappush(free_rooms, intervals[0][1])
# for loop in intervals except the first meeting time
for i in intervals[1:]:
#we have two situations, if current end time smaller than next start time, which means not overlap, we can share room, so pop the end time in free_rooms
if free_rooms[0] <= i[0]:
heapq.heappop(free_rooms)
#当前endtime <= 下一个starttime,则不overlap,去掉最早的
# the opposite situation, push the second end time into the heap, next time we can compare with it.
heapq.heappush(free_rooms,i[1])
# the len of free_rooms is the minimum number of conference rooms
return len(free_rooms)
# time complicity is O(n)