两个数组,一个存start,一个存end,分别sort。如果当前start >= end[last],说明这个start可以和上一个end用一间meeting room,不用加房间,所有直接last++。end数组里面代表着meeting的结束时间从早到晚的排序,而比较开始时间与最早的结束时间(end[last])就能得到是否需要加一个房间。
用两个array:
class Solution {
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length == 0 || intervals[0].length == 0)return 0;
int count = 1;
int[] end = new int[intervals.length];
int[] start = new int[intervals.length];
for (int i = 0; i < intervals.length; i++) {
start[i] = intervals[i][0];
end[i] = intervals[i][1];
}
Arrays.sort(start);
Arrays.sort(end);
int last = 0;
for (int i = 1; i < start.length; i++) {
if (last < end.length && start[i] >= end[last]) {
last++;
} else {
count++;
}
}
return count;
}
}
用priorityqueue做:
class Solution {
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length == 0 || intervals[0].length == 0)return 0;
Arrays.sort(intervals, (int[] a, int[] b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
//放入pq里代表多加了一个meeting room 拿出来代表当前meeting结束不占用meeting room
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(intervals[0][1]);
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] >= pq.peek()) {
pq.poll();
}
pq.offer(intervals[i][1]);
}
return pq.size();
}
}