Guest User

Untitled

a guest
Dec 14th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. public int minMeetingRooms(Interval[] intervals) {
  2. if (intervals == null || intervals.length == 0)
  3. return 0;
  4.  
  5. // Sort the intervals by start time
  6. Arrays.sort(intervals, new Comparator<Interval>() {
  7. public int compare(Interval a, Interval b) { return a.start - b.start; }
  8. });
  9.  
  10. // Use a min heap to track the minimum end time of merged intervals
  11. PriorityQueue<Interval> heap = new PriorityQueue<Interval>(intervals.length, new Comparator<Interval>() {
  12. public int compare(Interval a, Interval b) { return a.end - b.end; }
  13. });
  14.  
  15. // start with the first meeting, put it to a meeting room
  16. heap.offer(intervals[0]);
  17.  
  18. for (int i = 1; i < intervals.length; i++) {
  19. // get the meeting room that finishes earliest
  20. Interval interval = heap.poll();
  21.  
  22. if (intervals[i].start >= interval.end) {
  23. // if the current meeting starts right after
  24. // there's no need for a new room, merge the interval
  25. interval.end = intervals[i].end;
  26. } else {
  27. // otherwise, this meeting needs a new room
  28. heap.offer(intervals[i]);
  29. }
  30.  
  31. // don't forget to put the meeting room back
  32. heap.offer(interval);
  33. }
  34.  
  35. return heap.size();
  36. }
Advertisement
Add Comment
Please, Sign In to add comment