Time-Based Key-Value Store
设计一个key-value, 其中的value有一个timestamp, 每次输入key取value的时候, 取和当前timestamp最相近的value(floor).
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 |
class TimeMap { private HashMap<String, TreeMap<Integer, String>> m; /** Initialize your data structure here. */ public TimeMap() { m = new HashMap<>(); } public void set(String key, String value, int timestamp) { m.putIfAbsent(key, new TreeMap<Integer, String>()); m.get(key).put(timestamp, value); } public String get(String key, int timestamp) { if(!m.containsKey(key)) return ""; Integer i = m.get(key).floorKey(timestamp); if(i == null) return ""; return m.get(key).get(i); } } /** * Your TimeMap object will be instantiated and called as such: * TimeMap obj = new TimeMap(); * obj.set(key,value,timestamp); * String param_2 = obj.get(key,timestamp); */ |