-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTime_Based_Key-Value_Store.cpp
More file actions
51 lines (44 loc) · 1.27 KB
/
Time_Based_Key-Value_Store.cpp
File metadata and controls
51 lines (44 loc) · 1.27 KB
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
#include "unordered_map"
#include "string"
#include "vector"
using namespace std;
class TimeMap {
private:
unordered_map<string, vector<pair<int, string>>> ds;
string binarySearch(vector<pair<int, string>>& kv, int begin, int end, int target) {
int median = (begin+end)/2;
if (begin > end) {
if (end < 0) {
return "";
} else {
return kv[end].second;
}
}
if (target == kv[median].first) {
return kv[median].second;
} else if (target > kv[median].first) {
return binarySearch(kv, median+1, end, target);
} else {
return binarySearch(kv, begin, median-1, target);
}
}
public:
TimeMap() {
}
void set(string key, string value, int timestamp) {
ds[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
if (ds.find(key) != ds.end()) {
return binarySearch(ds[key], 0, ds[key].size()-1, timestamp);
} else {
return "";
}
}
};
/**
* 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);
*/