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]], returnfalse.

这道题给了我们一堆会议的时间,问我们能不能同时参见所有的会议,这实际上就是求区间是否有交集的问题,我们可以先给所有区间排个序,用起始时间的先后来排,然后我们从第二个区间开始,如果开始时间早于前一个区间的结束时间,则说明会议时间有冲突,返回false,遍历完成后没有冲突,则返回true.

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def canAttendMeetings(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        // Sort the intervals by start time
        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

Complexity Analysis

  • Time complexity :O(nlog n) The time complexity is dominated by sorting. Once the array has been sorted, onlyO(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.

Last updated

Was this helpful?