【Leetcode】253. Meeting Rooms II

1 第一步是按照起始时间对intervals进行排序

2 使用堆来处理,初始化堆和初始化一个list是一样的

3 扫描intervals里的所有interval,如果interval.start>=heap[0],则不需要新建一个meeting room,所以就用interval.end替换掉heap[0],用heapq.heapreplace,也就是先pop再push。

4 如果interval.start<=heap[0],则需要新建一个room,使用heapq.heappush将interval.end push进去

5 需要注意的是,当heap为空的时候,是需要先把第一个interval.end push到堆里去的,所以在第一个if的时候,要判断heap是否为空

6 这里用的是heap而不是stack,这是因为heap是priority queue,最小的元素在最顶端,而在这题中,我们heap里面放的是interval.end,interval.end越小的越提前结束,所以下一个interval需要和提前结束的对比。但stack是先进先出,就没有这个优势


要判断heap是否为空

原来start,end在这里定义了的







heap顶端值是heap[0]

stack顶端值是stack[-1]




Here is my thought. whenever there is a start meeting, we need to add one room. But before adding rooms, we check to see if any previous meeting ends, which is why we check start with the first end. When the start is bigger than end, it means at this time one of the previous meeting ends, and it can take and reuse that room. Then the next meeting need to compare with the second end because the first end's room is already taken. One thing is also good to know: meetings start is always smaller than end. Whenever we pass a end, one room is released.



你可能感兴趣的:(【Leetcode】253. Meeting Rooms II)