- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeBasedKeyValueStore.java
More file actions
Latest commit
59 lines (54 loc) · 1.77 KB
/
Copy pathTimeBasedKeyValueStore.java
File metadata and controls
59 lines (54 loc) · 1.77 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
52
53
54
55
56
57
58
59
importjava.util.Comparator;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.PriorityQueue;
classTimeMap {
privateMap<String, String> map;
privateMap<String, PriorityQueue<Integer>> timestamps;
publicTimeMap() {
map = newHashMap<>();
timestamps = newHashMap<>();
}
publicvoidset(Stringkey, Stringvalue, inttimestamp) {
map.put(key + "at timestamp: " + timestamp, value);
if (!timestamps.containsKey(key)) {
timestamps.put(key, newPriorityQueue<>(Comparator.reverseOrder()));
timestamps.get(key).add(timestamp);
}
elseif (timestamps.containsKey(key)) {
timestamps.get(key).add(timestamp);
}
}
publicStringget(Stringkey, inttimestamp) {
StringactualKey = key + "at timestamp: " + timestamp;
if (map.containsKey(actualKey)) {
returnmap.get(actualKey);
}
else {
if (timestamps.get(key) == null) {
returnnewString();
}
Iterator<Integer> iterator = timestamps.get(key).iterator();
intnext = -1;
intcurr = -1;
while (iterator.hasNext()) {
curr = iterator.next();
if (curr < timestamp) {
next = curr;
returnmap.get(key + "at timestamp: " + next);
}
}
if (next == -1) {
returnnewString();
}
returnmap.get(key + "at timestamp: " + next);
}
}
}
/**
* 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);
*/