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.Example
Example1
Input: intervals = [(0,30),(5,10),(15,20)]
Output: 2
Explanation:
We need two meeting rooms
room1: (0,30)
room2: (5,10),(15,20)
Example2
Input: intervals = [(2,7)]
Output: 1
Explanation:
Only need one meeting room
Code (Java):1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | /** * Definition of Interval: * public classs Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } * } */ public class Solution { /** * @param intervals: an array of meeting time intervals * @return: the minimum number of conference rooms required */ public int minMeetingRooms(List<Interval> intervals) { if (intervals == null || intervals.size() == 0 ) { return 0 ; } List<Event> events = new ArrayList<>(); for (Interval interval : intervals) { events.add( new Event(interval.start, 0 )); events.add( new Event(interval.end, 1 )); } Collections.sort(events, new MyEventComparator()); int ans = 0 ; int activeMeetings = 0 ; for (Event event : events) { if (event.flag == 0 ) { activeMeetings++; } else { activeMeetings--; } ans = Math.max(ans, activeMeetings); } return ans; } } class Event { int time; int flag; // 0 start, 1 end public Event( int time, int flag) { this .time = time; this .flag = flag; } } class MyEventComparator implements Comparator<Event> { @Override public int compare(Event a, Event b) { if (a.time != b.time) { return a.time - b.time; } return b.flag - a.flag; } } |
No comments:
Post a Comment