252. 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
.
链接: http://leetcode.com/problems/meeting-rooms/
题解:
一开始以为是跟Course Schedule一样,仔细读完题目以后发现只要sort一下就可以了。写得还不够精简,需要好好研究一下Java8的lambda表达式。
Time Complexity - O(nlogn), Space Complexity - O(1)
/** * 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 t1, Interval t2) { if(t1.start != t2.start) return t1.start - t2.start; else return t1.end - t2.end; } }); for(int i = 1; i < intervals.length; i++) { if(intervals[i].start < intervals[i - 1].end) return false; } return true; } }
二刷:
也是先对interval数组进行先startdata再enddate的排序,之后一次遍历数组来看是否intervals[i].start < intervals[i - 1].end。
用lambda表达式以后发现好慢
Java:
Time Complexity - O(nlogn), Space Complexity - O(1)
/** * 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) { return true; } Arrays.sort(intervals, (Interval i1, Interval i2) -> i1.start != i2.start ? i1.start - i2.start : i1.end - i2.end); for (int i = 1; i < intervals.length; i++) { if (intervals[i].start < intervals[i - 1].end) { return false; } } return true; } }
三刷:
Java:
/** * 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, (Interval i1, Interval i2) -> i1.start != i2.start ? i1.start - i2.start : i1.end - i2.end); for (int i = 1; i < intervals.length; i++) { if (intervals[i].start < intervals[i - 1].end) return false; } return true; } }
Reference:
https://leetcode.com/discuss/50912/ac-clean-java-solution