Created
November 13, 2018 06:49
-
-
Save hsaputra/f876ad5790c9b9162cc572f57af8c340 to your computer and use it in GitHub Desktop.
Meeting Rooms II - https://leetcode.com/problems/meeting-rooms-ii/description/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; } | |
* } | |
*/ | |
class Solution { | |
public int minMeetingRooms(Interval[] intervals) { | |
if (intervals == null || intervals.length == 0) { | |
return 0; | |
} | |
// Min heap | |
PriorityQueue<Integer> allocator = | |
new PriorityQueue<Integer>( | |
intervals.length, new Comparator<Integer>() { | |
public int compare(Integer a, Integer b) { | |
return a - b; | |
} | |
}); | |
// Lets sort on start time, and end if equals | |
Arrays.sort(intervals, new Comparator<Interval>() { | |
public int compare(Interval i1, Interval i2) { | |
if (i1.start == i2.start) { | |
return i1.end - i2.end; | |
} else { | |
return i1.start - i2.start; | |
} | |
} | |
}); | |
// Add the first meeting | |
allocator.add(intervals[0].end); | |
// Iterate over remaining intervals | |
for (int i = 1; i < intervals.length; i++) { | |
Interval curInterval = intervals[i]; | |
// check if we could pop the meeting room on top. | |
if (curInterval.start >= allocator.peek()) { | |
allocator.poll(); | |
} | |
// If a new room is to be assigned, then also we add to the heap, | |
// If an old room is allocated, then also we have to add to the heap with updated end time. | |
allocator.add(intervals[i].end); | |
} | |
return allocator.size(); | |
} | |
} |
Author
hsaputra
commented
Nov 13, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment