-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathDesign Log Storage System.java
More file actions
67 lines (59 loc) 路 2.12 KB
/
Copy pathDesign Log Storage System.java
File metadata and controls
67 lines (59 loc) 路 2.12 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
class LogSystem {
private static final Map<String, Integer> GRANULARITY_MAP = Map.of(
"Year", 0,
"Month", 1,
"Day", 2,
"Hour", 3,
"Minute", 4,
"Second", 5
);
private final TreeMap<Long, List<Integer>> map;
public LogSystem() {
this.map = new TreeMap<>();
}
public void put(int id, String timestamp) {
int[] numerics = Arrays.stream(timestamp.split(":"))
.mapToInt(Integer::parseInt)
.toArray();
map.computeIfAbsent(convert(numerics), _ -> new ArrayList<>()).add(id);
}
public List<Integer> retrieve(String start, String end, String granularity) {
List<Integer> result = new ArrayList<>();
long startTime = calculateGranularity(start, granularity, false);
long endTime = calculateGranularity(end, granularity, true);
for (List<Integer> ids : map.subMap(startTime, endTime).values()) {
result.addAll(ids);
}
return result;
}
private long convert(int[] numerics) {
numerics[1] = numerics[1] - (numerics[1] == 0 ? 0 : 1);
numerics[2] = numerics[2] - (numerics[2] == 0 ? 0 : 1);
return (numerics[0] - 1999L) * (31 * 12) * 24 * 60 * 60 +
numerics[1] * 31 * 24 * 60 * 60 +
numerics[2] * 24 * 60 * 60 +
numerics[3] * 60 * 60 +
numerics[4] * 60 +
numerics[5];
}
private long calculateGranularity(String s, String granularity, boolean end) {
String[] result = {"1999", "00", "00", "00", "00", "00"};
String[] splits = s.split(":");
for (int i = 0; i <= GRANULARITY_MAP.get(granularity); i++) {
result[i] = splits[i];
}
int[] numerics = Arrays.stream(result)
.mapToInt(Integer::parseInt)
.toArray();
if (end) {
numerics[GRANULARITY_MAP.get(granularity)]++;
}
return convert(numerics);
}
}
/**
* Your LogSystem object will be instantiated and called as such:
* LogSystem obj = new LogSystem();
* obj.put(id,timestamp);
* List<Integer> param_2 = obj.retrieve(start,end,granularity);
*/