Create a timebased key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)
- Stores the
keyandvalue, 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 (
"").
Example 1:
Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation: TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1); // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"
Example 2:
Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]
Note:
- All key/value strings are lowercase.
- All key/value strings have length in the range
[1, 100] - The
timestampsfor allTimeMap.setoperations are strictly increasing. 1 <= timestamp <= 10^7TimeMap.setandTimeMap.getfunctions will be called a total of120000times (combined) per test case.
這道題讓我們實現一種基於時間的鍵值對兒數據結構,有兩種操作 set 和 get,其中 set 就是存入鍵值對兒,同時需要保存時間戳,get 就是查找值,但此時不僅提供了 key 值,還提供了查詢的時間戳,返回值的時間戳不能大於查詢的時間戳,假如有多個相同值,返回時間戳最大的那個,若查詢不到就返回空。實際上這道題考察的就是較為復雜一些的數據結構,因為要同時保存三個量,而且還要提供快速查詢功能,可以使用 Map of Maps 的數據結構,外層可以使用一個 HashMap,因為對於 key 值沒有順序要求,而內層要使用一個 TreeMap,因為時間戳的順序很重要。在 set 函數中直接將數據插入數據結構中,在 get 中,用一個 upper_bound 來進行快速查找第一個大於目標值的位置,往后退一位,就是不大於目標值的位置。但是在退之前要判斷得到的位置是否是起始位置,是的話就沒法再往前退一位了,直接返回空串,不是的話可以退一位並返回即可,參見代碼如下:
class TimeMap {
public:
TimeMap() {}
void set(string key, string value, int timestamp) {
dataMap[key].insert({timestamp, value});
}
string get(string key, int timestamp) {
auto it = dataMap[key].upper_bound(timestamp);
return it == dataMap[key].begin() ? "" : prev(it)->second;
}
private:
unordered_map<string, map<int, string>> dataMap;
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/981
參考資料:
https://leetcode.com/problems/time-based-key-value-store/
https://leetcode.com/problems/time-based-key-value-store/discuss/226663/TreeMap-Solution-Java
