253. Meeting Rooms II

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)
                
        
        
        
       

        
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值