[LeetCode] 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
.
给一个会议时间区间的数组,问一个人是否能参加所有的会议。就是求这些区间是否有交集,如果有就不能参加所有的会,没有交集就可以参加所有的会议。
解法:先把区间按开始时间排序,然后判断每一个区间的开始时间是否比前一个会议的结束时间早,如果有,就是时间重叠。
Java:
public boolean canAttendMeetings(Interval[] intervals) { Arrays.sort(intervals, new Comparator<Interval>(){ public int compare(Interval a, Interval b){ return a.start-b.start; } }); for(int i=0; i<intervals.length-1; i++){ if(intervals[i].end>intervals[i+1].start){ return false; } } return true; }
Python:
# Time: O(nlogn) # Space: O(n) # # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param {Interval[]} intervals # @return {boolean} def canAttendMeetings(self, intervals): intervals.sort(key=lambda x: x.start) for i in xrange(1, len(intervals)): if intervals[i].start < intervals[i-1].end: return False return True
C++:
class Solution { public: bool canAttendMeetings(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b){return a.start < b.start;}); for (int i = 1; i < intervals.size(); ++i) { if (intervals[i].start < intervals[i - 1].end) { return false; } } return true; } };
类似题目:
[LeetCode] 253. Meeting Rooms II 会议室 II
All LeetCode Questions List 题目汇总