Description
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
.
Solution
Greedy, time O(n * logn), space O(n)
贪心思路,按照start对数组排序,另外用MinHeap维护现有的meeting room占用情况(几点结束)。
遍历数组,对于每个当前最早开始的meeting来说,都尝试用当前最早结束的meeting room来进行merge(这个其实很好理解,因为这个room如果不被它用,那么后面的meeting会更晚开始,没好处)。如果时间有重叠,那么给当前meeting新开一个meeting room。
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public int minMeetingRooms(Interval[] intervals) {
if (intervals == null || intervals.length == 0) {
return 0;
}
// sort the intervals by start time
Arrays.sort(intervals, (a, b) -> (a.start - b.start));
// use a min heap to track the minimum end time of conflict intervals
PriorityQueue<Interval> queue
= new PriorityQueue<>((a, b) -> (a.end - b.end));
for (Interval interval : intervals) {
if (queue.isEmpty()) {
queue.offer(interval);
continue;
}
// get the meeting room that finishes earliest
Interval earliest = queue.poll();
if (interval.start >= earliest.end) {
// if the current meeting starts right after
// there's no need for a new room, merge the interval
earliest.end = interval.end;
} else {
// otherwise, this meeting needs a new room
queue.offer(interval);
}
// don't forget to put the meeting room back
queue.offer(earliest);
}
return queue.size();
}
}
可以看出,由于intervals已经按照start排序,那么Queue中保存end即可,代码简化如下:
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public int minMeetingRooms(Interval[] intervals) {
if (intervals == null || intervals.length == 0) {
return 0;
}
Arrays.sort(intervals, (a, b) -> a.start - b.start);
PriorityQueue<Integer> queue = new PriorityQueue<>(); // store end times
for (Interval interval : intervals) {
if (queue.isEmpty() || interval.start < queue.peek()) {
// if no meeting room opened or even the earliest finished meeting room won't fit
queue.offer(interval.end);
} else {
// if the current meeting starts right after
// there's no need for a new room, merge the interval
queue.poll();
queue.offer(interval.end);
}
}
return queue.size();
}
}