-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path981.time-based-key-value-store.java
executable file
·46 lines (40 loc) · 1.25 KB
/
981.time-based-key-value-store.java
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
package Java;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
// @lc code=start
class TimeMap {
private static final String DEFAULT_VALUE = "";
private final HashMap<String, TreeMap<Integer, String>> map;
/** Initialize your data structure here. */
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
TreeMap<Integer, String> timeMap;
if (map.containsKey(key)) {
timeMap = map.get(key);
} else {
timeMap = new TreeMap<>();
map.put(key, timeMap);
}
timeMap.put(timestamp, value);
}
public String get(String key, int timestamp) {
if (map.containsKey(key)) {
TreeMap<Integer, String> timeMap = map.get(key);
Integer floorKey = timeMap.floorKey(timestamp);
if (floorKey != null) {
return timeMap.get(floorKey);
}
}
return DEFAULT_VALUE;
}
}
/**
* 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);
*/
// @lc code=end