Skip to content

Commit 1b75bc2

Browse files
committed
- Add: Java Time Based Key-Value Store
1 parent f6d69ae commit 1b75bc2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class TimeMap {
2+
Map<String, List<Data>> map = new HashMap<>() {
3+
@Override
4+
public List<Data> get(Object key) {
5+
if (!containsKey(key)) return new ArrayList<Data>();
6+
else return super.get(key);
7+
}
8+
};
9+
10+
public TimeMap() {} //SC: O(n), where n is the number of timestamp data
11+
12+
public void set(String key, String value, int ts) {
13+
if (!map.containsKey(key)) {
14+
map.put(key, new ArrayList<>());
15+
}
16+
map.get(key).add(new Data(value, ts));
17+
} //TC: O(1)
18+
19+
public String get(String key, int ts) {
20+
List<Data> values = map.get(key);
21+
String res = "";
22+
23+
int start = 0;
24+
int end = values.size() - 1;
25+
while (start <= end) {
26+
int mid = (start + end) / 2;
27+
if (values.get(mid).ts <= ts) {
28+
res = values.get(mid).value;
29+
start = mid + 1;
30+
} else {
31+
end = mid - 1;
32+
}
33+
}
34+
return res;
35+
} //TC: O(logn), where n is the number of timestamp in current key list
36+
}
37+
class Data {
38+
int ts = 0;
39+
String value = "";
40+
41+
Data(String value, int ts) {
42+
this.ts = ts;
43+
this.value = value;
44+
}
45+
}
46+
47+
/**
48+
* Your TimeMap object will be instantiated and called as such:
49+
* TimeMap obj = new TimeMap();
50+
* obj.set(key,value,timestamp);
51+
* String param_2 = obj.get(key,timestamp);
52+
*/

0 commit comments

Comments
 (0)