题目地址:
https://leetcode.com/problems/time-based-key-value-store/
要求设计一个能存储键值对的数据结构(与普通HashMap一样,键是唯一的),但是还需要考虑插入时候的时间戳。要求可以实现如下操作:
1、TimeMap()
初始化这个数据结构;
2、void set(String key, String value, int timestamp)
在给定的时间戳存储该键值对;
3、String get(String key, int timestamp)
,返回该key对应的所有value中,时间戳中最大的小于等于timestamp的那个value。如果不存在则返回空串。
可以用HashMap<String, TreeMap<Integer, String>>的方式来解决,外层Map解决key对应哪些value的问题,内层Map解决找到floorKey的问题。代码如下:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class TimeMap {
Map<String, TreeMap<Integer, String>> map;
/**
* Initialize your data structure here.
*/
public TimeMap() {
map = new HashMap<>();
}
public void set(String key, String value, int timestamp) {
map.putIfAbsent(key, new TreeMap<>());
map.get(key).put(timestamp, value);
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) {
return "";
}
TreeMap<Integer, String> treeMap = map.get(key);
Map.Entry<Integer, String> entry = treeMap.floorEntry(timestamp);
return entry == null ? "" : entry.getValue();
}
}
两个操作时间复杂度都是 O ( log n ) O(\log n) O(logn)。