Sunday, August 6, 2017

[Leetcode] 253. Meeting Rooms II

This problem is standard. But there are two points to make:

  1. sort function, passing key argument
  2. heap in python

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.
# 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
        """
        if len(intervals) <= 1: return len(intervals)
        
        intervals.sort(key=lambda x: x.start)
        h = []
        heapq.heappush(h, intervals[0].end)
        
        for i in intervals[1:]:
            if i.start >= h[0]:
                # update
                cur_endtime = heapq.heappop(h)
                cur_endtime = i.end
                heapq.heappush(h, cur_endtime)
            else:
                heapq.heappush(h, i.end)
        #print h
        return len(h)
        


No comments:

Post a Comment