forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeBasedKeyValueStore.java
More file actions
65 lines (52 loc) · 1.52 KB
/
TimeBasedKeyValueStore.java
File metadata and controls
65 lines (52 loc) · 1.52 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
60
61
62
63
64
65
package binary_search;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/time-based-key-value-store
* Difficulty: Medium
* Time complexity: O(log n)
* Space complexity: O(n)
*/
public class TimeBasedKeyValueStore {
private final Map<String, List<Node>> map;
public TimeBasedKeyValueStore() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
map.computeIfAbsent(key, k -> new ArrayList<>())
.add(new Node(value, timestamp));
}
public String get(String key, int timestamp) {
List<Node> list = map.get(key);
if (list == null) return "";
return search(list, timestamp);
}
private String search(List<Node> list, int target) {
int left = 0;
int right = list.size() - 1;
String result = "";
while (left <= right) {
int mid = (left + right) / 2;
if (list.get(mid).timestamp == target) {
return list.get(mid).value;
}
if (list.get(mid).timestamp > target) {
right = mid - 1;
} else {
result = list.get(mid).value;
left = mid + 1;
}
}
return result;
}
private static class Node {
String value;
int timestamp;
public Node(String v, int t) {
value = v;
timestamp = t;
}
}
}