-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimebasedKeyValue.java
More file actions
45 lines (34 loc) · 948 Bytes
/
timebasedKeyValue.java
File metadata and controls
45 lines (34 loc) · 948 Bytes
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
class TimeMap {
class Pair {
int timestamp;
String value;
Pair(int t, String v) {
timestamp = t;
value = v;
}
}
Map<String, List<Pair>> map;
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
map.putIfAbsent(key, new ArrayList<>());
map.get(key).add(new Pair(timestamp, value));
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) return "";
List<Pair> list = map.get(key);
int l = 0, r = list.size() - 1;
String res = "";
while (l <= r) {
int mid = l + (r - l) / 2;
if (list.get(mid).timestamp <= timestamp) {
res = list.get(mid).value;
l = mid + 1;
} else {
r = mid - 1;
}
}
return res;
}
}