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.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
最小堆。O(nLogn), O(n)
预处理:先把interval按照interval的start从小到大排好序。开一个最小堆,使得堆顶是end最小的interval。
遍历intervals,把当前interval的start和堆顶的end对比,如果交叉,说明不能用最早结束的会议室从而要重开一个新房间,入当前,heap.size()多了1说明多一个会议室;如果不交叉,说明可以之前那个房间开会的人走了我可以直接用那个房间了,出堆顶入当前,heap.size()不变说明不用多会议室。
返回的答案也就是这个过程中heap.size()的巅峰值,打擂台得到。
实现
/** * 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, new Comparator<Interval>() { @Override public int compare(Interval a, Interval b) { return a.start - b.start; } }); PriorityQueue<Interval> minHeap = new PriorityQueue<>(new Comparator<Interval>() { @Override public int compare(Interval a, Interval b) { return a.end - b.end; } }); int ans = 1; minHeap.offer(intervals[0]); for (int i = 1; i < intervals.length; i++) { int earliestEnd = minHeap.peek().end; if (intervals[i].start >= earliestEnd) { minHeap.poll(); minHeap.offer(intervals[i]); } else { minHeap.offer(intervals[i]); } ans = Math.max(ans, minHeap.size()); } return ans; } }