leetcode253 - Meeting Rooms II - medium
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.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]] Output: 1
Min heap. 先依据start time sort intervals, 之后依据end time开一个最小堆。遍历处理好的intervals,比较当前interval的start time和堆顶(end time), 如果end >= start,那就可以接着这个room继续用,pop堆顶(相当于清空这个房间给别人),否则别pop(相当于重新开一个房间),每次都把当前interval的end time push进去。最后heap size就是需要的房间数。
c++里pq是max heap by default,min heap用struct greater即可。
sort custom objects最方便用lambda expression
// generic lambda, operator() is a template with two parameters
auto glambda = [](auto& a, auto& b) { return a < b; };
Detour一下。堆即一个完全二叉树,每个子树也满足一个堆数。如果父节点总是大于等于子节点就是最大堆,反之父节点总是小于等于子节点就是最小堆。插入/删除O(logn)
实现:Time O(nlogn) Space O(n)
class Solution { public: int minMeetingRooms(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b){return a[0] < b[0];}); priority_queue<int, vector<int>, greater<int>> pq; for (auto interval : intervals){ if (!pq.empty() && pq.top() <= interval[0]){ pq.pop(); } pq.push(interval[1]); } return pq.size(); } };

浙公网安备 33010602011771号