码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Meeting Rooms II

时间:2016-02-22 13:33:14      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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.

Meeting Rooms类似。

排序后从前向后扫描。同时维护一个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         Arrays.sort(intervals, new Comparator<Interval>(){
16            public int compare(Interval i1, Interval i2){
17                if(i1.start == i2.start){
18                    return i1.end - i2.end;
19                }
20                return i1.start - i2.start;
21            } 
22         });
23         
24         int maxOverlap = 0;
25         //Min Heap
26         PriorityQueue<Integer> que = new PriorityQueue<Integer>();
27         for(int i = 0; i<intervals.length; i++){
28             que.add(intervals[i].end);
29             while(!que.isEmpty() && intervals[i].start >= que.peek()){
30                 que.poll();
31             }
32             maxOverlap = Math.max(maxOverlap, que.size());
33         }
34         return maxOverlap;
35     }
36 }

 

LeetCode Meeting Rooms II

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5206676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!