类似的题:JobHopper-MergeIntervals_laserljy123的博客-CSDN博客
所有类似问题:
56. Merge Intervals
57. Insert Interval (hard)
252. Meeting Rooms
253. Meeting Rooms II
729. My Calendar I
731. My Calendar II
732. My Calendar III (hard)
这道题看着简单,其实 抽象起来 很棘手。
刚看到题时,在纸上画了画,理解的题意是,在任意时间点,找出占用资源数 最大的值。图形大概是:n 条 横线 (n intervals), 然后从左到右 用竖线 去扫,然后记录最大值。
顺着这个思路想,非常难抽象。最后只能参考了别人答案。
1. start, end 是interval 的两个属性
interval 就是 resource request event
start 表示 开始占用资源
end 表示 释放资源。
2. start 可以作为 timeline 的先后顺序
3. 依次 check 所有 end,看是否能够在 最先结束 (!!!) 的资源释放时,得到这个资源。如果能就保持了之前的资源占用量,如果不能就需要增加 一个 资源占用量。
4. 因为这个model 并不是不 我一开始想的 扫遍 所有时间点,而是在 有新的 resource request event 来的时候 才去check resource. 所有最后 扫遍 所有 event 时
有了这个模型,剩下的就是 怎么 维护这个 quene 里面,总能查到 最先释放的资源 时刻。heapq (priority queue in JAVA) 能够满足这个 要求。
具体用法:
【python】详解python数据结构堆(heapq)库使用_brucewong0516的博客-CSDN博客
Python heapq库的用法介绍_Python碎片的博客-CSDN博客_heapq库
常见的:
1. 把 非空 array 转化成 heap.
heap = [...]
heapq.heapify(arr)
2. 加入新元素
heapq.heappush(arr, new_elem)
3. pop 最小的元素
heapq.heappop(heap)
4. 弹出最小元素,并且加入新元素
heapq.heapreplace(heap, new_elem)
from typing import List
import heapq
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
# sort by the endTime, small pq
# bug: intervals.sort(key=lambda x:x[1])
intervals.sort(key=lambda x: x[0])
heap = []
for interval in intervals:
# condition for: pop out the endTime (release the resource), and add the new endTime, the heap size did not change
if heap and interval[0] >= heap[0]:
heapq.heapreplace(heap, interval[1])
# condition to push new endTime (occupy more resource)
else:
heapq.heappush(heap, interval[1])
return len(heap)
def main():
solution = Solution()
intervals = [[1, 10], [2, 5], [3, 4]]
expected = 3
assert(solution.minMeetingRooms(intervals) == expected)