-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC981_TimeBasedKey_ValueStore.java
More file actions
104 lines (82 loc) · 2.77 KB
/
LC981_TimeBasedKey_ValueStore.java
File metadata and controls
104 lines (82 loc) · 2.77 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
101
102
103
104
package practise.src.main.java.leetCode;
import java.util.*;
import java.util.*;
public class LC981_TimeBasedKey_ValueStore {
// Helper class
static class Data {
String val;
int time;
Data(String val, int time) {
this.val = val;
this.time = time;
}
}
// TimeMap implementation
static class TimeMap {
private Map<String, List<Data>> map;
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
map.computeIfAbsent(key, k -> new ArrayList<>())
.add(new Data(value, timestamp));
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) return "";
return binarySearch(map.get(key), timestamp);
}
private String binarySearch(List<Data> list, int time) {
int left = 0, right = list.size() - 1;
while (left < right) {
int mid = (left + right + 1) >>> 1;
if (time < list.get(mid).time) {
right = mid - 1;
} else {
left = mid;
}
}
return list.get(left).time <= time ? list.get(left).val : "";
}
}
// Simulates LeetCode input/output
public static void main(String[] args) {
String[] operations = {
"TimeMap", "set", "get", "get", "set", "get", "get"
};
Object[][] values = {
{},
{"foo", "bar", 1},
{"foo", 1},
{"foo", 3},
{"foo", "bar2", 4},
{"foo", 4},
{"foo", 5}
};
List<Object> output = new ArrayList<>();
TimeMap timeMap = null;
for (int i = 0; i < operations.length; i++) {
switch (operations[i]) {
case "TimeMap":
timeMap = new TimeMap();
output.add(null);
break;
case "set":
timeMap.set(
(String) values[i][0],
(String) values[i][1],
(int) values[i][2]
);
output.add(null);
break;
case "get":
String result = timeMap.get(
(String) values[i][0],
(int) values[i][1]
);
output.add(result);
break;
}
}
System.out.println(output);
}
}