Meeting Room
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
.
分析:
即判断这些区间是否有重叠,遍历一遍,前一个区间的右边界不大于后一个区间的左边界即可,时间复杂度O(n),空间复杂度O(1)
代码:
bool canAttendAll(vector<vector<int> > time) { for(int i = 1; i < time.size(); i++) if(time[i][0] < time[i - 1][1]) return false; return true; }
Meeting Room 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
.
分析:
典型贪心法问题,尝试3种方案:1、开始时间优先,可行;2、结束时间优先,可以找到反例,[2,5][4,6][6,10][5,12],2个房间即可,可用该解法得要3个房间,故否决;3、持续时间优先,可以找到反例,[4,5][4,6][6,10][5,12],2个房间即可,可用该解法需要3个房间,故否决;
解法:
开始时间优先
证明:
有[x1, y1],[x2, y2],x1 < x2,y1 > x2,得开两个房间;对于[x3, y3],[x4, y4],必有x4 >= x3 >= x2。那么,若x3 >= y1,将[x3, y3]归入[x1, y1]房间中,则如果x4 < y2,那么x3 < y2,若交换[x3, y3]和[x4, y4]的顺序,还是必然还得多开一个房间,结果无差别;若x4 >= y2,可以将 [x4, y4]归入[x2, y2]房间中,交换[x3, y3]和[x4, y4]的顺序,结果并不会更好,反而可能更差。故开始时间优先的方法是最优的。
代码:
bool cmp(vector<int> &a, vector<int> &b) { return a[0] < b[0]; } int roomCount(vector<vector<int> > time) { if(time.empty()) return 0; sort(time.begin(), time.end(), cmp); vector<int> room(1, INT_MIN); int count = 1; for(auto t : time) { bool openNew = true; for(int &r : room) { if(r <= t[0]) { r = t[1]; openNew = false; break; } } if(openNew) { count++; room.push_back(t[1]); } } return count; }