一刷273-二分模块-981. 基于时间的键值存储(m)

本文介绍了一个基于时间的键值数据结构TimeMap的实现,该结构使用哈希表嵌套TreeMap来存储键值对,TreeMap以降序排列时间戳,确保在给定时间戳下能快速找到之前的最大时间戳对应的值。TimeMap类提供了set方法用于存储键值对和时间戳,get方法则根据时间戳返回对应的值。示例展示了TimeMap的使用场景和操作流程。
摘要由CSDN通过智能技术生成
题目:
设计一个基于时间的键值数据结构,该结构可以在不同时间戳存储对应同一个键的多个值,
并针对特定时间戳检索键对应的值。

实现 TimeMap 类:
TimeMap() 初始化数据结构对象

void set(String key, String value, int timestamp)
			 存储键 key、值 value,以及给定的时间戳 timestamp。
			 
String get(String key, int timestamp)
			返回先前调用 set(key, value, timestamp_prev) 所存储的值,
			其中 timestamp_prev <= timestamp 。
			
如果有多个这样的值,则返回对应最大的  timestamp_prev 的那个值。
如果没有值,则返回空字符串("")。
-----------------------
示例:
输入:
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
输出:
[null, null, "bar", "bar", null, "bar2", "bar2"]

解释:
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1);  // 存储键 "foo" 和值 "bar" ,时间戳 timestamp = 1   
timeMap.get("foo", 1);         // 返回 "bar"
timeMap.get("foo", 3);         // 返回 "bar", 因为在时间戳 3 和时间戳 2 处没有对应 "foo" 的值,所以唯一的值位于时间戳 1 处(即 "bar") 。
timeMap.set("foo", "bar2", 4); // 存储键 "foo" 和值 "bar2" ,时间戳 timestamp = 4  
timeMap.get("foo", 4);         // 返回 "bar2"
timeMap.get("foo", 5);         // 返回 "bar2"
 
提示:
1 <= key.length, value.length <= 100
key 和 value 由小写英文字母和数字组成
1 <= timestamp <= 107
set 操作中的时间戳 timestamp 都是严格递增的
最多调用 set 和 get 操作 2 * 105--------------------
思路:
嵌套一个哈希表,不过嵌套进去的哈希表需要让 key 降序排列,
也就是将 timestamp 按照降序排列下来。
TreeMap是默认对key进行递增排序的,所以检查的话只要检查到大于x的第一个位置就好
--------------------
class TimeMap {//哈希嵌套哈希 里面嵌套一个treeMap  TreeMap是默认对key进行递增排序的
    private Map<String, TreeMap<Integer, String>> data;//嵌套哈希
    public TimeMap() {
        data = new HashMap<>();//初始化
    }
    public void set(String key, String value, int timestamp) {
        TreeMap<Integer, String> treeMap = data.getOrDefault(key, new TreeMap<>((o1, o2) -> o2 - o1));//检查有无哈希表, 有就添加, 没有就 new 一个再添加  从大到小排序
        treeMap.put(timestamp, value);
        data.put(key, treeMap);
    }
    public String get(String key, int timestamp) {
        TreeMap<Integer, String> treeMap= data.get(key);
        if (treeMap== null || treeMap.isEmpty()) return "";//!! treeMap.isEmpty()
        else {
            for (int time : treeMap.keySet()) {//从上到下挨个检查 time
                if (time <= timestamp) {//若检查到的time < timestamp, 就找到了
                    return treeMap.get(time);
                }
            }
        }
        return "";
    }
}
/**
 * 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);
 */

LC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值