LeetCode Meeting Rooms II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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.

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的主要内容,如果未能解决你的问题,请参考以下文章

Meeting Rooms II -- LeetCode

Leetcode 253: Meeting Rooms II

LeetCode-Meeting Rooms II

[LeetCode] Meeting Rooms II 会议室之二

leetcode253 - Meeting Rooms II - medium

253. Meeting Rooms II