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
Solution & Analysis
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.
先排序,再遍历
Sort, then compare last.end vs. current.start; similar to Merge Intervals
/** * 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; } * } */classSolution {publicbooleancanAttendMeetings(Interval[] intervals) {Arrays.sort(intervals,newComparator<Interval>() {publicintcompare(Interval i1,Interval i2) {returni1.start-i2.start; } });Interval last =null;for (Interval i: intervals) {if (last !=null&&i.start<last.end) {returnfalse; } last = i; }returntrue; }}
publicbooleancanAttendMeetings(Interval[] intervals) {// Sort the intervals by start timeArrays.sort(intervals, (x, y) ->x.start-y.start);for (int i =1; i <intervals.length; i++)if (intervals[i-1].end> intervals[i].start)returnfalse;returntrue;}