253. Meeting Rooms II

79 阅读1分钟

image.png

方法

如果一个会议开始的时间晚于或等于另一个会议结束的时间,那么可以在同一个会议室举行这两个会议。

  • we can keep all the rooms in a min heap where the key for the min heap would be the ending time of meeting.

  • So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.

  • If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.

  • After processing all the meetings, the size of the heap will tell us the number of rooms allocated. This will be the minimum number of rooms needed to accommodate all the meetings. why?因为遍历过的meeting要么已经结束然后被后面的会议占用同一个room,要么还在进行留在pq中

class Solution {
    public int minMeetingRooms(int[][] intervals) {
        // 按照开始时间排序
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        // 默认小顶堆, 存放结束时间
        Queue<Integer> pq = new PriorityQueue<>();

        for (int[] interval : intervals) {
            if (!pq.isEmpty() && interval[0] >= pq.peek()) {
                pq.poll(); // 目前最早结束的那个会议室已经完事了,可以占用
            }
            pq.offer(interval[1]);
        }
        
        return pq.size();
    }
}