一、题目
创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:
-
set(string key, string value, int timestamp)
- 存储键 key、值 value,以及给定的时间戳 timestamp。
-
get(string key, int timestamp)
- 返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp。
- 如果有多个这样的值,则返回对应最大的 timestamp_prev 的那个值。
- 如果没有值,则返回空字符串("")。
点击查看原题
难度级别: 中等
二、思路
1)HashMap+TreeMap
善于使用数据结构可以快速解题,使用HashMap
的特性,可以快速找到key
对应的entry
,由于要找到小于等于给定timestamp
的value
,使用TreeMap
的特性可以快速找到
三、代码
1)HashMap+TreeMap
class TimeMap {
private Map<String, TreeMap<Integer, String>> map;
public TimeMap() {
map = new HashMap<String, TreeMap<Integer, String>>();
}
public void set(String key, String value, int timestamp) {
// if (!map.containsKey(key)) {
// map.put(key, new TreeMap<Integer, String>());
// }
// map.get(key).put(timestamp, value); // 可化简为下面一行
map.computeIfAbsent(key, k -> new TreeMap<Integer, String>()).put(timestamp, value);
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) {
return "";
}
Map.Entry<Integer, String> entry = map.get(key).floorEntry(timestamp);
if (entry == null) {
return "";
}
return entry.getValue();
}
时间复杂度为O(nlogC)
,C
是单个key
中不同值的数量,空间复杂度为O(n)