边工作边刷题:70天一遍leetcode: day 92-2

Meeting Rooms I/II

要点:这题和skyline类似,利用了interval start有序的特点,从左向右处理,用一个heap来动态表示当前占用rooms的时间段,所以heap的size就是room数。具体来说,

  • heap是end time的min heap,如果新的interval.start超过min end,那么同一房间可以被这个interval重用。而重叠就需要新房间,只push heap。
  • 只需要和最小的end比较,因为只需要知道是否有至少一个可重用,如果可以重用,不改变上限
  • 这个解法类似Rearrange array to certain distance:?
  • 当然用endPoint sort + count的方法也可以。都是O(nlgn),但不需要heap
# Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

# For example,
# Given [[0, 30],[5, 10],[15, 20]],
# return 2.

# Hide Company Tags Google Facebook
# Hide Tags Heap Greedy Sort
# Hide Similar Problems (H) Merge Intervals (E) Meeting Rooms

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

class Solution(object):
    def minMeetingRooms(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: int
        """
        meetings = []
        intervals.sort(key=lambda interval:interval.start)
        count = 0
        while i in intervals:
            if not meetings or meetings[0]>i.start:
                heappush(meetings, i.end)
                i+=1
            else:
                heappop(meetings)
            count = max(count, len(meetings))
        
        return count

错误点:不管是否pop,都要push新的:either 占新room or replace旧room

# 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.

# Hide Company Tags Facebook
# Hide Tags Sort
# Hide Similar Problems (H) Merge Intervals (M) Meeting Rooms II


# 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
        """
        # intervals = sorted(intervals, key=lambda interval: interval.start)
        intervals.sort(key=lambda interval: interval.start)
        for i in xrange(1, len(intervals)):
            if intervals[i].start<intervals[i-1].end:
                return False
        return True

还有一类类似的题,是room (or 资源)有限,如何选最多的meeting。

posted @ 2016-04-09 06:14  absolute100  阅读(134)  评论(0编辑  收藏  举报