-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path981TimeBasedKeyValueStore.java
More file actions
100 lines (82 loc) · 2.39 KB
/
981TimeBasedKeyValueStore.java
File metadata and controls
100 lines (82 loc) · 2.39 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//https://leetcode.com/problems/time-based-key-value-store/
class TreeMapSolution {
TreeMap<String, TreeMap<Integer, String>> treeMap;
public TreeMapSolution() {
treeMap = new TreeMap();
}
public void set(String key, String value, int timestamp) {
if (!treeMap.containsKey(key)) {
treeMap.put(key, new TreeMap<Integer, String> ());
}
treeMap.get(key).put(timestamp, value);
}
public String get(String key, int timestamp) {
TreeMap<Integer, String> lst = treeMap.get(key);
if (lst == null) {
return "";
}
if (lst.containsKey(timestamp)) {
return lst.get(timestamp);
}
Map.Entry<Integer, String> entry = lst.lowerEntry(timestamp);
return entry == null ? "" : entry.getValue();
}
}
class BinarySearchSolution {
Map<String, List<Pair<String, Integer>>> map;
public BinarySearchSolution() {
map = new HashMap();
}
public void set(String key, String value, int timestamp) {
if (!map.containsKey(key)) {
map.put(key, new ArrayList<Pair<String, Integer>> ());
}
List lst = map.get(key);
lst.add(new Pair<>(value, timestamp));
map.put(key, lst);
}
public String get(String key, int timestamp) {
List<Pair<String, Integer>> lst = map.get(key);
return lst == null ? "" : binarySearch(lst, timestamp);
}
String binarySearch(List<Pair<String, Integer>> lst, int timestamp) {
int start = 0, end = lst.size() - 1;
if (lst.get(start).getValue() > timestamp) {
return "";
}
while (start<= end) {
int mid = start + (end - start) / 2;
if (lst.get(mid).getValue() == timestamp) {
return lst.get(mid).getKey();
}
if (lst.get(mid).getValue() > timestamp) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return lst.get(end).getKey();
}
}
class TimeMap {
TreeMapSolution treeMapSolution;
BinarySearchSolution binarySearchSolution;
public TimeMap() {
treeMapSolution = new TreeMapSolution();
binarySearchSolution = new BinarySearchSolution();
}
public void set(String key, String value, int timestamp) {
//treeMapSolution.set(key, value, timestamp);
binarySearchSolution.set(key, value, timestamp);
}
public String get(String key, int timestamp) {
//return treeMapSolution.get(key, timestamp);
return binarySearchSolution.get(key, timestamp);
}
}
/**
* 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);
*/