解題思路
這題必須用到 map,然後因為還有 timestamp,要在時限內的話要用到 binary search。
從這題中學到:
1. unordered_map 可以用來加速、提升效率
2. upper_bound 可以用來找到第一個大於給定數值的
3. auto iterator 可以用 -- 移到上一個
程式碼
class TimeMap { public: unordered_map<string, map<int, string>> mp; TimeMap() { } void set(string key, string value, int timestamp) { mp[key][timestamp] = value; } string get(string key, int timestamp) { if(!mp.count(key)) return ""; auto it = mp[key].upper_bound(timestamp); if(it == mp[key].begin()) return ""; return (--it)->second; } };