Skip to content

Commit de464b8

Browse files
authored
Create time-based-key-value-store.cpp
1 parent 72f3ad0 commit de464b8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/time-based-key-value-store.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: set: O(1)
2+
// get: O(logn)
3+
// Space: O(n)
4+
5+
class TimeMap {
6+
public:
7+
/** Initialize your data structure here. */
8+
TimeMap() {
9+
10+
}
11+
12+
void set(string key, string value, int timestamp) {
13+
lookup_[key].emplace_back(timestamp, value);
14+
}
15+
16+
string get(string key, int timestamp) {
17+
if (!lookup_.count(key)) {
18+
return "";
19+
}
20+
auto it = upper_bound(lookup_[key].cbegin(),
21+
lookup_[key].cend(),
22+
make_pair(timestamp + 1, ""),
23+
[](const pair<int, string>& lhs,
24+
const pair<int, string>& rhs) {
25+
return lhs.first < rhs.first;
26+
});
27+
return it != lookup_[key].cbegin() ? prev(it)->second : "";
28+
}
29+
30+
private:
31+
unordered_map<string, vector<pair<int, string>>> lookup_;
32+
};
33+
34+
/**
35+
* Your TimeMap object will be instantiated and called as such:
36+
* TimeMap* obj = new TimeMap();
37+
* obj->set(key,value,timestamp);
38+
* string param_2 = obj->get(key,timestamp);
39+
*/
40+

0 commit comments

Comments
 (0)