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.
For example,
Given [[0, 30],[5, 10],[15, 20]],
return false.
一刷
先根据start时间排序,再判断有没有overlap
/**
* 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; }
* }
*/
public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
if(intervals.length<=1) return true;
Arrays.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b){ return a.start - b.start;}
});
Interval cur = intervals[0];
for(int i=1; i<intervals.length; i++){
if(intervals[i].start<cur.end) return false;
cur = intervals[i];
}
return true;
}
}
二刷
同上
/**
* 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; }
* }
*/
public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
if(intervals == null || intervals.length == 0) return true;
Arrays.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b){
if(a.start == b.start) return b.end - a.end;
else return a.start - b.start;
}
});
int end = intervals[0].end;
for(int i=1; i<intervals.length; i++){
if(end > intervals[i].start) return false;
end = intervals[i].end;
}
return true;
}
}