LeetCode 252. Meeting Rooms
原题链接在这里:https://leetcode.com/problems/meeting-rooms/
题目:
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
.
题解:
对array进行排序,从i = 1开始判断start是否在前一个end之前, 若是就return false. 完成loop返回true.
Time Complexity: O(nlogn). Space: O(1).
AC Java:
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 public class Solution { 11 public boolean canAttendMeetings(Interval[] intervals) { 12 if(intervals == null || intervals.length == 0){ 13 return true; 14 } 15 Arrays.sort(intervals, new Comparator<Interval>(){ 16 public int compare(Interval i1, Interval i2){ 17 if(i1.start == i2.start){ 18 return i1.end - i2.end; 19 } 20 return i1.start - i2.start; 21 } 22 }); 23 24 for(int i = 1; i<intervals.length; i++){ 25 if(intervals[i].start < intervals[i-1].end){ 26 return false; 27 } 28 } 29 return true; 30 } 31 }
跟上Meeting Rooms II, Maximum Number of Events That Can Be Attended.