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.
Like the previous one Meeting Room, still need to sort the intervals using a comparator.
We need to simulate the process to know the maximum number of conference rooms needed.
We need to maintain a minimal heap, which sort the intervals according to their finishing time.
We add the interval to this heap one by one since they have already been sorted according to their start time.
So this heap acctually simulates the conference rooms, the number of elements it has instataneously is the number of rooms required.
Every time we add one interval to this heap, we need to check if its start time is greater than or equal to heap.peek(). If it is, that means there‘s some conferences in the heap which end now, and their rooms should be released.
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 public class Solution { 11 public int minMeetingRooms(Interval[] intervals) { 12 if (intervals==null || intervals.length==0) return 0; 13 Comparator<Interval> comp = new Comparator<Interval>() { 14 public int compare(Interval i1, Interval i2) { 15 return (i1.start==i2.start)? i1.end-i2.end : i1.start-i2.start; 16 } 17 }; 18 19 Arrays.sort(intervals, comp); 20 PriorityQueue<Interval> heap = new PriorityQueue<Interval>(intervals.length, new Comparator<Interval>() { 21 public int compare(Interval i1, Interval i2) { 22 return (i1.end==i2.end)? i1.start-i2.start : i1.end-i2.end; 23 } 24 }); 25 26 int maxNum = 0; 27 for (int i=0; i<intervals.length; i++) { 28 if (heap.size() == 0) { 29 heap.offer(intervals[i]); 30 maxNum = Math.max(maxNum, heap.size()); 31 } 32 else if (intervals[i].start >= heap.peek().end) { 33 heap.poll(); 34 i--; 35 } 36 else { 37 heap.offer(intervals[i]); 38 maxNum = Math.max(maxNum, heap.size()); 39 } 40 } 41 return maxNum; 42 } 43 }
原文:http://www.cnblogs.com/EdwardLiu/p/5065569.html