力扣981.基于时间的键值存储
-
哈希表存键值和时间戳
- 二分找到位置
-
class TimeMap { unordered_map<string,vector<pair<string,int>>> cnt; public: TimeMap() { } void set(string key, string value, int timestamp) { cnt[key].emplace_back(make_pair(value,timestamp)); } string get(string key, int timestamp) { if(cnt.count(key)) { auto &p = cnt[key]; int l=0,r=p.size(); while(l<r) { int mid = l + r >> 1; if(p[mid].second > timestamp) r = mid; else l = mid + 1; } if(l == 0) return ""; return p[l-1].first; } else return ""; } };