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
return
Given
[[0, 30],[5, 10],[15, 20]]
,return
2
.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 static compare(Interval a, Interval b){ | |
return a.start<b.start; | |
} | |
int minMeetingRooms(vector<Interval>& intervals) { | |
if(intervals.size()==0) | |
return 0; | |
sort(intervals.begin(), intervals.end(), compare); | |
vector<vector<Interval> > classRoom; | |
auto cmp = [](pair<int, int> a, pair<int, int> b) {return a.first > b.first;}; | |
priority_queue<pair<int, int>, std::vector<pair<int, int> >, decltype(cmp)> mypq(cmp); | |
for(int i=0; i<intervals.size(); i++){ | |
Interval itv = intervals[i]; | |
if(mypq.empty()){ | |
vector<Interval> newRoom; | |
newRoom.push_back(itv); | |
mypq.push(pair<int, int> (itv.end, newRoom.size()-1)); | |
classRoom.push_back(newRoom); | |
continue; | |
} | |
pair<int, int> top = mypq.top(); | |
if(itv.start >= top.first){ | |
classRoom[top.second].push_back(itv); | |
mypq.pop(); | |
mypq.push(pair<int, int> (itv.end, top.second)); | |
}else{ | |
vector<Interval> newRoom; | |
newRoom.push_back(itv); | |
mypq.push(pair<int, int> (itv.end, newRoom.size()-1)); | |
classRoom.push_back(newRoom); | |
} | |
} | |
return classRoom.size(); | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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>& itvs) { | |
int res = 0; | |
if(itvs.empty()) | |
return res; | |
sort(itvs.begin(), itvs.end(), [](Interval a, Interval b){return a.start<b.start;}); | |
priority_queue<int> myPQ; | |
for(int i=0; i<itvs.size(); i++){ | |
Interval itv = itvs[i]; | |
if(myPQ.empty()){ | |
myPQ.push(itv.end*-1); | |
res++; | |
}else{ | |
int early = myPQ.top()*-1; | |
if(early<=itv.start){ | |
myPQ.pop(); | |
myPQ.push(itv.end*-1); | |
}else{ | |
res++; | |
myPQ.push(itv.end*-1); | |
} | |
} | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment