原题链接:https://leetcode.com/problems/meeting-rooms/
1. Description
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],…] (si < ei), determine if a person could attend all meetings.
Example 1:
Input: [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: [[7,10],[2,4]]
Output: true
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
2. Solution
Sorting
The idea here is to sort the meetings by starting time. Then, go through the meetings one by one and make sure that each meeting ends before the next one starts.
Time complexity : O(nlogn). The time complexity is dominated by sorting. Once the array has been sorted, only O(n) time is taken to go through the array and determine if there is any overlap.
Space complexity : O(1). Since no additional space is allocated.
from: https://leetcode.com/problems/meeting-rooms/solution/
Write quick sort function by myself.
code
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
quickSort(intervals, 0, intervals.length-1);
for(int i = 0; i <intervals.length-1;i++){
if(intervals[i][1] > intervals[i+1][0] ){
return false;
}
}
return true;
}
//quick sort every intervals based on the first element
public void quickSort(int [][] a ,int l ,int r){
if(l > r){
return ;
}
int x = a[l][0];
int y = a[l][1];
int i = l;
int j = r;
//let all elements bigger than or equal to x move behind of x
//let all elements smaller than x move in front of x
while(i < j){
// from tail to head
while(i < j && a[j][0] >= x){
j--;
}
if( i < j ){
//swap a[j][0] and a[i][0]
int [] swap = swap(a[i][0], a[j][0]);
a[i][0] = swap[0];
a[j][0] = swap[1];
//swap a[j][1] and a[i][1];
swap = swap(a[i][1], a[j][1]);
a[i][1] = swap[0];
a[j][1] = swap[1];
i++;
}
// from head to tail
while(i < j && a[i][0] < x){
i++;
}
if(i < j){
//swap a[j][0] and a[i][0]
int [] swap = swap(a[i][0], a[j][0]);
a[i][0] = swap[0];
a[j][0] = swap[1];
//swap a[j][1] and a[i][1];
swap = swap(a[i][1], a[j][1]);
a[i][1] = swap[0];
a[j][1] = swap[1];
j--;
}
}
a[i][0] = x;
a[i][1] = y;
//next, we need to divide and conquer
quickSort(a, l, i-1 );
quickSort(a, i+1, r);
}
public int [] swap(int a,int b){
int temp = a;
a = b;
b = temp;
return new int []{ a, b};
}
}
Reference
https://leetcode.com/problems/meeting-rooms/solution/