|
| 1 | +/** |
| 2 | + * Definition for an interval. public class Interval { int start; int end; Interval() { start = 0; |
| 3 | + * end = 0; } Interval(int s, int e) { start = s; end = e; } } |
| 4 | + */ |
| 5 | +class Solution { |
| 6 | + |
| 7 | + /* public int minMeetingRooms(Interval[] intervals) { |
| 8 | +
|
| 9 | + // Check for the base case. If there are no intervals, return 0 |
| 10 | + if (intervals.length == 0) { |
| 11 | + return 0; |
| 12 | + } |
| 13 | + // Min heap |
| 14 | + PriorityQueue<Integer> allocator = |
| 15 | + new PriorityQueue<Integer>( |
| 16 | + intervals.length, |
| 17 | + new Comparator<Integer>() { |
| 18 | + public int compare(Integer a, Integer b) { |
| 19 | + return a - b; |
| 20 | + } |
| 21 | + }); |
| 22 | +
|
| 23 | + // Sort the intervals by start time |
| 24 | + Arrays.sort( |
| 25 | + intervals, |
| 26 | + new Comparator<Interval>() { |
| 27 | + public int compare(Interval a, Interval b) { |
| 28 | + return a.start - b.start; |
| 29 | + } |
| 30 | + }); |
| 31 | + // Add the first meeting |
| 32 | + allocator.add(intervals[0].end); |
| 33 | +
|
| 34 | + // Iterate over remaining intervals |
| 35 | + for (int i = 1; i < intervals.length; i++) { |
| 36 | + // If the room due to free up the earliest is free, assign that room to this meeting. |
| 37 | + if (intervals[i].start >= allocator.peek()) { |
| 38 | + allocator.poll(); |
| 39 | + } |
| 40 | + // If a new room is to be assigned, then also we add to the heap, |
| 41 | + // If an old room is allocated, then also we have to add to the heap with updated end time. |
| 42 | + allocator.add(intervals[i].end); |
| 43 | + } |
| 44 | + // The size of the heap tells us the minimum rooms required for all the meetings. |
| 45 | + return allocator.size(); |
| 46 | + }*/ |
| 47 | + |
| 48 | + public int minMeetingRooms(Interval[] intervals) { |
| 49 | + int ans = 0, curr = 0; |
| 50 | + List<TimePoint> timeline = new ArrayList<>(); |
| 51 | + for (Interval interval: intervals) { |
| 52 | + timeline.add(new TimePoint(interval.start, 1)); |
| 53 | + timeline.add(new TimePoint(interval.end, -1)); |
| 54 | + } |
| 55 | + timeline.sort(new Comparator<TimePoint>() { |
| 56 | + public int compare(TimePoint a, TimePoint b) { |
| 57 | + if (a.time != b.time) return a.time - b.time; |
| 58 | + else return a.room - b.room; |
| 59 | + } |
| 60 | + }); |
| 61 | + for (TimePoint t: timeline) { |
| 62 | + curr += t.room; |
| 63 | + if (curr >= ans) ans = curr; |
| 64 | + } |
| 65 | + return ans; |
| 66 | + } |
| 67 | + |
| 68 | + private class TimePoint { |
| 69 | + int time; |
| 70 | + int room; |
| 71 | + |
| 72 | + TimePoint(int time, int room) { |
| 73 | + this.time = time; |
| 74 | + this.room = room; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments