forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0981-time-based-key-value-store.cpp
53 lines (43 loc) · 1.21 KB
/
0981-time-based-key-value-store.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Design time-based key-value structure, multiple vals at diff times
Hash map, since timestamps are naturally in order, binary search
Time: O(log n)
Space: O(n)
*/
class TimeMap {
public:
TimeMap() {
}
void set(string key, string value, int timestamp) {
m[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
if (m.find(key) == m.end()) {
return "";
}
int low = 0;
int high = m[key].size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (m[key][mid].first < timestamp) {
low = mid + 1;
} else if (m[key][mid].first > timestamp) {
high = mid - 1;
} else {
return m[key][mid].second;
}
}
if (high >= 0) {
return m[key][high].second;
}
return "";
}
private:
unordered_map<string, vector<pair<int, string>>> m;
};
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap* obj = new TimeMap();
* obj->set(key,value,timestamp);
* string param_2 = obj->get(key,timestamp);
*/