Meeting Rooms II

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.

Tips:

O(nlogn),因为要sort。

用heap来做,遍历interval,把end放进heap,count为1。如果后面有start的值大于heap.peek(),则count + 1。

Code:

/**
 * 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 == 0) {
            return 0;
        }
        Arrays.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
        int count = 1;
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        heap.offer(intervals[0].end);
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i].start < heap.peek()) {
                count++;
            }
            else {
                heap.poll();
            }
            heap.offer(intervals[i].end);            
        }
        return count;
    }
}

results matching ""

    No results matching ""