LeetCode 253. Meeting Rooms II

原题链接在这里:https://leetcode.com/problems/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.

题解:

排序后扫描,同时维护一个min heap, 把每个interval 的end 放到min heap中. 若是新的interval start 大于 heap peek, 就一直heap poll.

maxOverlap是这个过程中heap size的峰值。

Time Complexity: O(nlogn). Space: O(n).

AC Java:

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution {
11     public int minMeetingRooms(Interval[] intervals) {
12         if(intervals == null || intervals.length == 0){
13             return 0;
14         }
15         
16         Arrays.sort(intervals, new Comparator<Interval>(){
17             public int compare(Interval i1, Interval i2){
18                 if(i1.start == i2.start){
19                     return i1.end - i2.end;
20                 }
21                 return i1.start - i2.start;
22             }
23         });
24         
25         int maxOverlap = 0;
26         PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
27         for(int i = 0; i<intervals.length; i++){
28             minHeap.add(intervals[i].end);
29             while(!minHeap.isEmpty() && minHeap.peek()<=intervals[i].start){
30                 minHeap.poll();
31             }
32             maxOverlap = Math.max(maxOverlap, minHeap.size());
33         }
34         return maxOverlap;
35     }
36 }

类似Car PoolingMeeting RoomsMaximum Number of Events That Can Be Attended.

posted @ 2016-02-22 11:51  Dylan_Java_NYC  阅读(783)  评论(0编辑  收藏  举报