LC 981. Time Based Key-Value Store
阿新 • • 發佈:2019-02-04
red timestamp multipl int pre ast fas sub hat
Create a timebased key-value store class TimeMap
, that supports two operations.
1. set(string key, string value, int timestamp)
- Stores the
key
andvalue
, along with the giventimestamp
.
2. get(string key, int timestamp)
- Returns a value such that
set(key, value, timestamp_prev)
was called previously, withtimestamp_prev <= timestamp
- If there are multiple such values, it returns the one with the largest
timestamp_prev
. - If there are no values, it returns the empty string (
""
).
class TimeMap { private: unordered_map<string, map<int, string>> mp; vector<int> tvec; public: /** Initialize your data structure here. */ TimeMap() {} void set(string key, string value, int timestamp) { mp[key][timestamp] = value; } string get(string key, inttimestamp) { if(!mp.count(key)) return ""; if(mp[key].count(timestamp)) return mp[key][timestamp]; for(auto it = mp[key].rbegin(); it != mp[key].rend(); it++) { if(it->first > timestamp) continue; else { return it->second; } } return ""; } };
LC 981. Time Based Key-Value Store