253. 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
.
此题非常经典,用了两种自定义排序,第一种是将原来数组按照start从小到大排列。第二种设置一个优先队列按照end从小到大进行排序。将排好序的数组的第一个元素插入优先队列中。将优先队列中的元素的end和数组后面的元素start进行比较,如果有重叠部分,则将数组后面的元素插入优先队列中,然后原优先队列中的元素也插入进去,接下来不断进行比较即可,如果没有重叠部分后将下一个元素的end值赋值给优先队列中的poll出来的第一个元素,代码如下:
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; 16 } 17 }; 18 Arrays.sort(intervals,comp); 19 PriorityQueue<Interval> pq = new PriorityQueue<>(new Comparator<Interval>(){ 20 public int compare(Interval i1,Interval i2){ 21 return i1.end-i2.end; 22 } 23 }); 24 pq.offer(intervals[0]); 25 for(int i=1;i<intervals.length;i++){ 26 Interval interval = pq.poll(); 27 if(intervals[i].start>=interval.end){ 28 interval.end = intervals[i].end; 29 }else{ 30 pq.offer(intervals[i]); 31 } 32 pq.offer(interval); 33 } 34 return pq.size(); 35 } 36 } 37 //the run time nlogn,the space complexity could be O(n);