forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path981-Time-Based-Key-Value-Store.java
More file actions
32 lines (27 loc) · 977 Bytes
/
981-Time-Based-Key-Value-Store.java
File metadata and controls
32 lines (27 loc) · 977 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
class TimeMap {
HashMap<String, List<Pair<String, Integer>>> map;
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
if (!map.containsKey(key)) map.put(key, new ArrayList<>());
map.get(key).add(new Pair(value, timestamp));
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) return "";
List<Pair<String, Integer>> list = map.get(key);
return search(list, timestamp);
}
public String search(List<Pair<String, Integer>> list, int timestamp) {
int start = 0;
int end = list.size() - 1;
while (start < end) {
int mid = start + (end - start + 1) / 2;
if (list.get(mid).getValue() <= timestamp) start = mid; else end =
mid - 1;
}
return list.get(start).getValue() <= timestamp
? list.get(start).getKey()
: "";
}
}