253. Meeting Rooms II
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了253. 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.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]] Output: 1
解题思路:
要最少的最多的房间,我们只要满足时段内重复最多的不同会议就好。
可以将会议开始和结束都存到最小堆里,用pair存储,第二个值用于标识是开始还是结束。
我从最小堆中取出堆顶元素(即最小值)
若其为起点,则rooms自增一;若其为重点,首先将当前rooms的值与ret相比,取最大的那个,然后rooms自减一。
还有一个很神奇的解法
代码:
用最小堆来解:
/** * 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) { priority_queue<pair<int,int>, vector<pair<int,int>>, greater<> > q; int ret = 0; for(Interval i : intervals){ q.push({i.start, 1}); //represent start q.push({i.end, -1}); //represent end } int rooms = 0; while(!q.empty()){ auto p = q.top(); q.pop(); if(p.second == 1){ //represent start rooms++; }else{ //represent end ret = max(ret, rooms); rooms--; } } return ret; } };
很神奇的解法:
/** * 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) { vector<int> starts, ends; int res = 0, endpos = 0; for (auto a : intervals) { starts.push_back(a.start); ends.push_back(a.end); } sort(starts.begin(), starts.end()); sort(ends.begin(), ends.end()); for (int i = 0; i < intervals.size(); ++i) { if (starts[i] < ends[endpos]) ++res; else ++endpos; } return res; } };
以上是关于253. Meeting Rooms II的主要内容,如果未能解决你的问题,请参考以下文章