设计日志存储系统
难度:
标签:
题目描述
代码结果
运行时间: 44 ms, 内存: 16.7 MB
/*
* Leetcode 635: Design Log Storage System
*
* Solution using Java Streams:
* 1. Use a list to store log entries as a pair of (id, timestamp).
* 2. Use a map to define the granularity levels (year, month, day, hour, minute, second).
* 3. For the retrieve function, use Java Streams to filter logs based on the given start and end timestamps according to the specified granularity.
*/
import java.util.*;
import java.util.stream.Collectors;
public class LogSystem {
private List<int[]> logs;
private Map<String, Integer> granularityMap;
public LogSystem() {
logs = new ArrayList<>();
granularityMap = new HashMap<>();
granularityMap.put("Year", 4);
granularityMap.put("Month", 7);
granularityMap.put("Day", 10);
granularityMap.put("Hour", 13);
granularityMap.put("Minute", 16);
granularityMap.put("Second", 19);
}
public void put(int id, String timestamp) {
logs.add(new int[]{id, timestamp.hashCode()});
}
public List<Integer> retrieve(String s, String e, String gra) {
int len = granularityMap.get(gra);
int startHash = s.substring(0, len).hashCode();
int endHash = e.substring(0, len).hashCode();
return logs.stream()
.filter(log -> log[1] >= startHash && log[1] <= endHash)
.map(log -> log[0])
.collect(Collectors.toList());
}
}
解释
方法:
这个题解使用了哈希表来存储日志的时间戳和对应的 ID。在插入日志时,直接将时间戳作为键,ID 作为值存入哈希表。在检索日志时,根据给定的时间范围和粒度,遍历哈希表中的所有键值对,将时间戳截取到对应粒度,如果在给定的时间范围内,就将对应的 ID 加入结果列表。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
在处理较大数据量时,遍历哈希表的所有键值对是否有可能导致性能问题?是否有更高效的数据结构或方法来优化检索过程?
▷