Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 22, 2017 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/75631237ec0446121791809686701926 to your computer and use it in GitHub Desktop.
Save jianminchen/75631237ec0446121791809686701926 to your computer and use it in GitHub Desktop.
Plan to study Meeting room II - Java code
public int minMeetingRooms(Interval[] intervals) {
if (intervals == null || intervals.length == 0)
return 0;
// Sort the intervals by start time
Arrays.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) { return a.start - b.start; }
});
// Use a min heap to track the minimum end time of merged intervals
PriorityQueue<Interval> heap = new PriorityQueue<Interval>(intervals.length, new Comparator<Interval>() {
public int compare(Interval a, Interval b) { return a.end - b.end; }
});
// start with the first meeting, put it to a meeting room
heap.offer(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
// get the meeting room that finishes earliest
Interval interval = heap.poll();
if (intervals[i].start >= interval.end) {
// if the current meeting starts right after
// there's no need for a new room, merge the interval
interval.end = intervals[i].end;
} else {
// otherwise, this meeting needs a new room
heap.offer(intervals[i]);
}
// don't forget to put the meeting room back
heap.offer(interval);
}
return heap.size();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment