File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TimeMap {
2
+ private Map <String , List <Node >> hm ;
3
+
4
+ public TimeMap () {
5
+ hm = new HashMap <>();
6
+ }
7
+
8
+ public void set (String key , String value , int timestamp ) {
9
+ hm .putIfAbsent (key , new ArrayList <>());
10
+ hm .get (key ).add (new Node (timestamp , value ));
11
+ }
12
+
13
+ public String get (String key , int timestamp ) {
14
+ if (!hm .containsKey (key )) {
15
+ return "" ;
16
+ }
17
+
18
+ List <Node > nodes = hm .get (key );
19
+ int low = 0 , high = nodes .size () - 1 ;
20
+
21
+ while (low < high ) {
22
+ int mid = low + (high - low ) / 2 ;
23
+
24
+ if (nodes .get (mid ).timestamp == timestamp ) {
25
+ return nodes .get (mid ).value ;
26
+ }
27
+
28
+ if (nodes .get (mid ).timestamp < timestamp ) {
29
+ if (nodes .get (mid + 1 ).timestamp > timestamp ) {
30
+ return nodes .get (mid ).value ;
31
+ }
32
+
33
+ low = mid + 1 ;
34
+ } else {
35
+ high = mid - 1 ;
36
+ }
37
+ }
38
+
39
+ return nodes .get (low ).timestamp <= timestamp ? nodes .get (low ).value : "" ;
40
+ }
41
+
42
+ private class Node {
43
+ private int timestamp ;
44
+ private String value ;
45
+
46
+ public Node (int t , String v ) {
47
+ timestamp = t ;
48
+ value = v ;
49
+ }
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments