Number of Meeting Rooms at a Given Time
当时准备Quora Onsite的题:以intervals的形式给一堆会议时间,然后给任意一个时间点,问该时间点会议的数量
由于所有的interval给定,没有添加或者删除的操作,这里就可以用hashtable来做,二分来找答案。
每个m[start]++, m[end]--,对于任意一个时刻,从最早累加至今的和就是当前会议的个数。然后就可以用二分快速查找。
#include <iostream> #include <vector> #include <map> using namespace std; // 以intervals的形式给一堆会议时间,然后给任意一个时间点,问该时间点会议的数量 struct Interval{ int start; int end; Interval(){start=0; end=0;} Interval(int s, int e):start(s),end(e){} }; int main(){ vector<Interval> intervals; intervals.push_back(Interval(1,5)); intervals.push_back(Interval(4,9)); intervals.push_back(Interval(2,3)); intervals.push_back(Interval(3,10)); intervals.push_back(Interval(9,10)); map<int,int> m; // time->num for (auto interval:intervals){ m[interval.start]++; m[interval.end]--; } int sum=0; for (auto it=m.begin();it!=m.end();++it){ it->second += sum; sum = it->second; } for (auto x:m) cout<<x.first<<' '<<x.second<<endl; int time=100; auto it=m.upper_bound(time); --it; cout << it->second << endl; return 0; }