My Calendar I
hash table + binary search,注意边界情况即可。
class MyCalendar { private: map<int,int> m; // map[start] -> end public: MyCalendar() {} bool book(int start, int end) { auto it=m.lower_bound(start); if (it!=m.end() && end>it->first) return false; if (it!=m.begin() && (--it)->second>start) return false; m[start] = end; return true; } }; /** * Your MyCalendar object will be instantiated and called as such: * MyCalendar* obj = new MyCalendar(); * bool param_1 = obj->book(start,end); */
My Calendar II
方法一:沿用 My Calendar I 的思路,给overlap的时间段再建一个hashtable,判断overlap的时间有没有overlap。
https://leetcode.com/problems/my-calendar-ii/discuss/109519/JavaC++-Clean-Code-with-Explanation
方法二:Boundary Count
思路与 Number of Meeting Rooms at a Given Time 一致,只不过每次book都要计算一遍所有时刻有没有符合要求。
class MyCalendarTwo { private: map<int,int> m; // time->num public: MyCalendarTwo() {} bool book(int start, int end) { ++m[start]; --m[end]; int sum=0; for (auto it=m.begin();it!=m.end();++it){ if (it->second+sum >= 3){ if (--m[start]==0) m.erase(start); ++m[end]; return false; } sum += it->second; } return true; } }; /** * Your MyCalendarTwo object will be instantiated and called as such: * MyCalendarTwo* obj = new MyCalendarTwo(); * bool param_1 = obj->book(start,end); */
时间复杂度 O(n^2)