forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
62 lines (46 loc) · 1.5 KB
/
main.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
54
55
56
57
58
59
60
61
62
/// Source : https://leetcode.com/problems/time-based-key-value-store/
/// Author : liuyubobobo
/// Time : 2019-01-26
#include <iostream>
#include <unordered_map>
#include <set>
/// Using TreeSet to store (time, value) pair information for each key
/// Time Complexity: init: O(1)
/// set: O(logn)
/// get: O(logn)
/// Space Complexity: O(n)
class TimeMap {
private:
std::unordered_map<std::string, std::set<std::pair<int, std::string>>> map; // key -> (time, value)
public:
/** Initialize your data structure here. */
TimeMap() {}
void set(std::string key, std::string value, int timestamp) {
map[key].insert(make_pair(timestamp, value));
}
std::string get(std::string key, int timestamp) {
std::set<std::pair<int, std::string>>::iterator iter =
map[key].lower_bound(std::make_pair(timestamp, ""));
if(iter == map[key].end() || iter->first > timestamp){
if(iter == map[key].begin()) return "";
iter --;
}
return iter->second;
}
};
int main() {
TimeMap timeMap;
timeMap.set("foo", "bar", 1);
std::cout << timeMap.get("foo", 1) << std::endl;
// bar
std::cout << timeMap.get("foo", 3) << std::endl;
// bar
timeMap.set("foo", "bar2", 4);
std::cout << timeMap.get("foo", 4) << std::endl;
// bar2
std::cout << timeMap.get("foo", 5) << std::endl;
// bar2
std::cout << timeMap.get("foo", 1) << std::endl;
// bar
return 0;
}