首页 > 代码库 > 253 Meeting Rooms II
253 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.
看到区间求重叠的部分 , 就想到对区间排序(start, end?), 然后用堆模拟遍历218 The Skyline Problem
Like the previous one Meeting Room, still need to sort the intervals using a comparator.
We need to simulate the process to know the maximum number of conference rooms needed.
We need to maintain a minimal heap, which sort the intervals according to their finishing time.
We add the interval to this heap one by one since they have already been sorted according to their start time.
So this heap acctually simulates the conference rooms, the number of elements it has instataneously is the number of rooms required.
Every time we add one interval to this heap, we need to check if its start time is greater than or equal to heap.peek(). If it is, that means there‘s some conferences in the heap which end now, and their rooms should be released.
/** * 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; Comparator<Interval> comp = new Comparator<Interval>() { public int compare(Interval i1, Interval i2) { return (i1.start==i2.start)? i1.end-i2.end : i1.start-i2.start; } }; Arrays.sort(intervals, comp); PriorityQueue <Integer> que = new PriorityQueue<Integer>( new Comparator<Integer>(){ public int compare ( Integer int1, Integer int2 ){ return int1 - int2; } }); int rooms = 0; for ( int i = 0; i < intervals.length; i ++ ){ while ( !que.isEmpty() && que.peek() <= intervals[ i ].start ){ que.poll(); } que.offer ( intervals[ i ].end ); rooms = Math.max ( rooms, que.size() ); } return rooms; } }
这道题有follow up问求最多interval的时间点,返回任意一个就行。
随便返回一个比如heap.size()最大的时候,heap.peek()
38行更新为
if(heap.size() > rooms)
rooms = heap.size();
maxMoment = heap.peak;
253 Meeting Rooms II