BiruLyu
7/26/2017 - 9:59 PM

## 253. Meeting Rooms II(#Greedy).java

``````/**
* 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; }
* }
*/
public class Solution {
public int minMeetingRooms(Interval[] intervals) {
if(intervals == null ) throw new IllegalArgumentException();
if(intervals.length <= 1) return intervals.length;
//sort by start
Arrays.sort(intervals, new Comparator<Interval>(){
public int compare(Interval l1, Interval l2){
return l1.start - l2.start;
}
});
Queue<Interval> pq = new PriorityQueue<>(new Comparator<Interval>(){
public int compare(Interval l1, Interval l2){
return l1.end - l2.end;
}
});
for(int i = 0; i < intervals.length; i ++){
if(pq.isEmpty()){
pq.offer(intervals[i]);
} else {
Interval cur = pq.peek();
if(cur.end <= intervals[i].start){
pq.poll();
}
pq.offer(intervals[i]);
}
}
return pq.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; }
* }
*/
public class Solution {
public int minMeetingRooms(Interval[] intervals) {
if (intervals == null || intervals.length < 1) return 0;
int len = intervals.length;
int[] starts = new int[len];
int[] ends = new int[len];

for (int i = 0; i < len; i++) {
starts[i] = intervals[i].start;
ends[i] = intervals[i].end;
}

Arrays.sort(starts);
Arrays.sort(ends);
int res = 0;
int endIdx = 0;
for (int i = 0; i < len; i++) {
if (starts[i] < ends[endIdx]) {
res++;
} else {
endIdx++;
}
}
return res;
}
}``````