# LeetCode 731. My Calendar II https://leetcode.com/problems/my-calendar-ii/description/ ## 題目大意 這題很像[LeetCode 729. My Calendar I](https://hackmd.io/@RyoukiWei/leetcode729) ## 思考 ### Algo 1 我們一樣用一個 map 但這次用的是時間跟次數的映射 ```cpp! class MyCalendarTwo { public: MyCalendarTwo() {} bool book(int start, int end) { ++events[start]; --events[end]; int booking = 0; for (const auto &event : events) { booking += event.second; if (!(booking < 3)) { --events[start]; ++events[end]; return false; } } return true; } private: map<int, int> events; }; ``` ## Algo 2 使用兩條 `vector<pair<int, int>>` ```cpp! class MyCalendarTwo { public: MyCalendarTwo() {} bool book(int start, int end) { for (const auto &overlap : overlaps) { if (start < overlap.second && end > overlap.first) return false; } for (const auto &event : events) { if (start < event.second && end > event.first) overlaps.emplace_back(max(start, event.first), min(end, event.second)); } events.emplace_back(start, end); return true; } private: vector<pair<int, int>> events; vector<pair<int, int>> overlaps; }; ``` 題目其實有說 At most `1000` calls will be made to book. 實際表現上 algo 2 也好了一點點 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up