252.Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...]
(si < ei), determine if a person could attend
all meetings.
For example,
Given [[0, 30],[5, 10],[15, 20]]
,
return false
.
解题思路:直接排序。然后比较。如果任何一个interval[i].start < interval[i-1].end就return false。
//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:
bool canAttendMeetings(vector<Interval>& intervals) {
int sz = intervals.size();
if (sz <= 1) {
return true;
}
sort(intervals.begin(), intervals.end(), comparator);
for (int i = 0; i < sz - 1; ++i) {
if (intervals[i].start == intervals[i + 1].start || intervals[i].end > intervals[i + 1].start) {
return false;
}
}
return true;
}
private:
static bool comparator(Interval i1, Interval i2) {
return i1.start < i2.start;
}
};
252.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
.
解题思路:先把start, end 都排序。然后如果start >= end,那么说明,start这一个会议,可以和end那一组会议公用一个会议室。然后,这个会议室的结束时间就不再是现在的end了。而要往后延。如果 start < end, 那么必须开一个会议室,counter++
class Solution
{
public:
int minMeetingRooms(vector<Interval>& intervals)
{
vector<int> starts, ends;
int counter = 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])++counter;
else ++endpos;
}
return counter;
}
};
最后是最小堆来解题的方法,这种方法先把所有的时间区间按照起始时间排序,然后新建一个最小堆,开始遍历时间区间,如果堆不为空,且首元素小于等于当前区间的起始时间,我们去掉堆中的首元素,把当前区间的结束时间压入堆,由于最小堆是小的在前面,那么假如首元素小于等于起始时间,说明上一个会议已经结束,可以用该会议室开始下一个会议了,所以不用分配新的会议室,遍历完成后堆中元素的个数即为需要的会议室的个数
class Solution {
public:
int minMeetingRooms(vector<Interval>& intervals) {
sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b){return a.start < b.start;});
priority_queue<int, vector<int>, greater<int>> q;
for (auto a : intervals) {
if (!q.empty() && q.top() <= a.start) q.pop();
q.push(a.end);
}
return q.size();
}
};