Meeting Rooms II

题目
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.

For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.

答案

思路

先把intervals按开始时间从小到大sort

任何intervals肯定至少需要1个房间
interval[0] will take that room initially

Then use a priority queue to keep track of the rooms, while each room is represented by end time of the meeting that is currently using the room.

int count = 1
Iterate through i to n - 1
1 peek the room r_least with least end time
2 if interval[i] would conflict with this room, it must conflict with any other room, then we need to open a new room (count++)
3 if no conflict, meeting at interval[i] will take this room, and poll the r_least from priority queue
4 In the end, we need to push interval[i] into the queue anyway, either to take a old room or open a new room.

return count as the answer, since it's the number of time we open a new room

代码

class Solution {
    public int minMeetingRooms(Interval[] intervals) {
        if(intervals == null || intervals.length == 0) return 0;
        
        // Sort array by start time, ascending order
        Arrays.sort(intervals, new Comparator() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        
        // Use a priority queue to keep track of rooms that are opened, and currently used by which meeting(i.e what's the meeting's end time)
        
        int count = 1;
        PriorityQueue pq = new PriorityQueue<>();
        pq.offer(intervals[0].end);
        
        for(int i = 1; i < intervals.length; i++) {
            int possible_availiable_room = pq.peek();
            if(intervals[i].start < possible_availiable_room)
                count++;
            else
                pq.poll();
            pq.offer(intervals[i].end);
        }
        return count;
    }
}

你可能感兴趣的:(Meeting Rooms II)