java - 使用时间概念实现地图
问题描述
我最近受到挑战,要使用以下两种方法实现数据结构:
set(key, value, time)
:在指定时间将键设置为值。
get(key, time)
:在指定时间或更早的时间获取 key 的值。
如果我们在特定时间设置一个键,它将永远保持该值,或者直到它稍后被设置。
例子
示例 1
d.set(1, 1, 0) // set key 1 to value 1 at time 0
d.set(1, 2, 2) // set key 1 to value 2 at time 2
d.get(1, 1) // get key 1 at time 1 should be 1
d.get(1, 3) // get key 1 at time 3 should be 2
示例 2
d.set(1, 1, 5) // set key 1 to value 1 at time 5
d.get(1, 0) // get key 1 at time 0 should be null
d.get(1, 10) // get key 1 at time 10 should be 1
示例 3
d.set(1, 1, 0) // set key 1 to value 1 at time 0
d.set(1, 2, 0) // set key 1 to value 2 at time 0
d.get(1, 0) // get key 1 at time 0 should be 2
解决方案
这是我的实现:
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* An Implementation a Map with the notion of Time.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
* @param <T> the type of time tracked by this map.
* T MUST implement {@link Comparable} to have a notion of comparing times.
* @author Hari Krishnan
* @see Map
* @see NavigableMap
*/
public class TimedMap<K, V, T extends Comparable<T>> {
private final Map<K, NavigableMap<T, V>> map = new HashMap<>();
/**
* Associates the specified value with the specified key at the specified time in this map.
* If the map previously contained a mapping for the key at this time,
* the old value is replaced by the specified value.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @param time time at which said association should occur
*/
public void set(K key, V value, T time) {
if (!map.containsKey(key))
map.put(key, new TreeMap<>());
map.get(key).put(time, value);
}
/**
* Returns the value to which the specified key is mapped at the specified time or earlier,
* or {@code null} if this map contains no mapping for the key at the specified time or earlier.
*
* @param key the key whose associated value is to be returned
* @param time the time(or earlier) at which the values associated with the key is to be returned.
* @return The value to which the specified key is mapped at the specified time or earlier, or
* {@code null} if this map contains no mapping for the key at the specified time or earlier.
*/
public V get(K key, T time) {
try {
return map.get(key).floorEntry(time).getValue();
} catch (NullPointerException ex) {
return null;
}
}
}
欢迎改进和建议!
推荐阅读
- android - Room : 带有日期条件的查询结果不正确
- html - 使每个 div 填充屏幕宽度的 1/6
- python - 熊猫:当我使用唯一索引应用一些 loc 操作时,“无法从重复轴重新索引”
- c# - OpenAndActivateDocument 生成 ArgumentException
- python - Matplotlib legend makes the image too large
- python - 在 pygame 中使用 vector2。与窗框碰撞,将球限制在矩形区域内
- python - 将带有字典的熊猫系列转换为数据帧,然后附加到原始数据帧
- android - 制作一个全局列表变量以从任何活动访问
- reactjs - 将 POST 从 React 发送到我在 Spring Boot 上运行的 localhost:8080
- javascript - 我在网页上的 mp4 背景并不总是开始播放