码迷,mamicode.com
首页 > 其他好文 > 详细

253. Meeting Rooms II

时间:2017-06-25 17:48:55      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:and   esc   ber   solution   script   turn   general   code   sel   

https://leetcode.com/problems/meeting-rooms-ii/#/solutions

 

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.

 

 

Sol:
 
Use heap data structure to store the end time of intervals. The length of heap is the number of rooms needed.
 
If the start time is later than the end time so far, then replace the value in the heap and no room is needed.
 
Otherwise, a new room is needed, and we achieve it by pushing the end time of the interval into the heap. 

 

 

# 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
        """
        
        intervals.sort(key = lambda x: x.start)
        # stores the end time of intervals
        heap = []
        for i in intervals:
            if heap and i.start >= heap[0]:
                # means two intervals can use the same room
                heapq.heapreplace(heap, i.end)
            else:
                # a new room is allocated
                heapq.heappush(heap, i.end)
        return len(heap)

 

 

Note:

 

1 heapq.heappop() in python can pop the smallest value in the heap. Here‘s the demo.

 

 

 

import heapq

 

h = []

heapq.heappush(h, 5)

heapq.heappush(h, 2)

heapq.heappush(h, 8)

heapq.heappush(h, 4)

print(heapq.heappop(h))

print(heapq.heappop(h))

 

 

== >

2

4

 

 

 

 

2 Data structures are generally based on the ability of a computer to fetch and store data at any place in its memory.

253. Meeting Rooms II

标签:and   esc   ber   solution   script   turn   general   code   sel   

原文地址:http://www.cnblogs.com/prmlab/p/7077199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!