Skip to content

Instantly share code, notes, and snippets.

@ali-alaei
Created January 23, 2022 09:58
Show Gist options
  • Save ali-alaei/b8d8653c3b19613471cc631bf0d83242 to your computer and use it in GitHub Desktop.
Save ali-alaei/b8d8653c3b19613471cc631bf0d83242 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Comparator;
public class Solution {
//A method to return the number of used rooms
public int minMeetingRooms(int[][] intervals) {
//If input == null, does not process it
if (intervals.length == 0) {
return 0;
}
//defining the start and end arrays
Integer[] start = new Integer[intervals.length];
Integer[] end = new Integer[intervals.length];
//Assigning values from the intervals array
//to the start and end array
for (int i = 0; i < intervals.length; i++) {
start[i] = intervals[i][0];
end[i] = intervals[i][1];
}
//Sort the start and end array in increasing order
Arrays.sort(
end,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return a - b;
}
});
Arrays.sort(
start,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return a - b;
}
});
//Pointers to loop over the start and end array
int startPointer = 0, endPointer = 0;
//The number of rooms
int usedRooms = 0;
//Loops over the arrays until it checks
//every meeting in the intervals array
while (startPointer < intervals.length) {
//If this is true, we have an empty room and
//do not require a new room for the meeting
if (start[startPointer] >= end[endPointer]) {
usedRooms -= 1;
endPointer += 1;
}
//Otherwise, we make an empty room to hold the meeting.
usedRooms += 1;
startPointer += 1;
}
//Returns the number of rooms used
return usedRooms;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment