题目链接:https://leetcode.com/problems/meeting-rooms-ii/
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
.
思路:每个区间的起始点代表一个区间的开始,会有可能将重叠区域+1,每个区间的结束点代表一个区间的结束,将会使重叠区域-1,因此我们可以利用这个性质,并结合STL的map来实现
代码如下:
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { map<int, int> mp; for(auto val: intervals) { mp[val.start]++; mp[val.end]--; } int cnt = 0, Max = 0; for(auto val: mp) { cnt += val.second; Max = max(cnt, Max); } return Max; } };参考:https://leetcode.com/discuss/58720/c-solution-using-a-map-total-11-lines
还可以用优先队列来做.首先对区间以start升序排列,然后遍历所有的区间,将每个区间的end加入小顶堆构成的优先队列.如果新的区间(start > que.top()),说明这个区间和之前的区间不重复,就可以将之前的end移除优先队列,否则就保留.一次最多删除和插入一次,因此优先队列最后剩余的元素个数就是最大重叠区间个数.
代码如下:
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){ return a.start < b.start;}); priority_queue<int, vector<int>, greater<int>> que; for(auto val: intervals) { if(!que.empty() && val.start >= que.top()) que.pop(); que.push(val.end); } return que.size(); } };参考:https://leetcode.com/discuss/64686/concise-c-solution-with-min_heap-sort-greedy