原题链接:https://leetcode.com/problems/meeting-rooms-ii/
1. Description
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 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
2. Solution
这个问题有一个非常简单的处理思路,我们可以先将上述的区间在坐标轴上画好,然后通过垂直于x轴的线从左向右移动,移动的过程中,记录这根线和区间相交的最大交点个数,这个最大交点个数就是相交的最大区间个数。
above words and picture are both from https://blog.csdn.net/qq_17550379/article/details/93459159
one of the test example is
1 13
13 15
the output should be 1 rather than 2
Thus the sorted two-dimensional array times should be like this:
1 1
13 -1
13 1
15 -1
rather than like this:
1 1
13 1
13 -1
15 -1
That is why what i did in when x[0] == y[0] in the @Override compare function.
code
class Solution {
public int minMeetingRooms(int[][] intervals) {
if(intervals == null || intervals.length==0){
return 0;
}
int n = intervals.length * 2;
int [][] times = new int [n][2];
int index = 0;
int roomNum = 0;
int maxroomNum = 0;
//count all start times and end times into Two-dimensional times
for(int i = 0; i<intervals.length ; i++){
//meeting start time, is 1
times[index][0] = intervals[i][0];
times[index++][1] = 1;
//meeting end time, is -1
times[index][0] = intervals[i][1];
times[index++][1] = -1;
}
//sort two-dimensional array times based on the first column
Arrays.sort(times, new Comparator<int[]>(){
@Override
public int compare(int[] x, int[] y){
if(x[0] > y[0]){
return 1;
}
else if(x[0] < y[0]){
return -1;
}
else{
if(x[1] > y[1]){
return 1;
}
else if(x[1] < y[1]){
return -1;
}
else{
return 0;
}
}
}
});
//scan the two-dimensional array time
//start time, meetingRoomNum +1;
//end time. meetingRoomNum -1;
//the maximum of meetingRoomNum is the answer;
for(int i = 0; i <n; i++){
roomNum += times[i][1];
if(roomNum > maxroomNum){
maxroomNum = roomNum;
}
}
return maxroomNum;
}
}
3. Reference
https://blog.csdn.net/qq_17550379/article/details/93459159