leetcode981. 基于时间的键值存储(treemap)

创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:

  1. set(string key, string value, int timestamp)

存储键 key、值 value,以及给定的时间戳 timestamp。
2. get(string key, int timestamp)

返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp。
如果有多个这样的值,则返回对应最大的 timestamp_prev 的那个值。
如果没有值,则返回空字符串("")。

示例 1:

输入:inputs = [“TimeMap”,“set”,“get”,“get”,“set”,“get”,“get”], inputs = [[],[“foo”,“bar”,1],[“foo”,1],[“foo”,3],[“foo”,“bar2”,4],[“foo”,4],[“foo”,5]]
输出:[null,null,“bar”,“bar”,null,“bar2”,“bar2”]
解释:
TimeMap kv;
kv.set(“foo”, “bar”, 1); // 存储键 “foo” 和值 “bar” 以及时间戳 timestamp = 1
kv.get(“foo”, 1); // 输出 “bar”
kv.get(“foo”, 3); // 输出 “bar” 因为在时间戳 3 和时间戳 2 处没有对应 “foo” 的值,所以唯一的值位于时间戳 1 处(即 “bar”)
kv.set(“foo”, “bar2”, 4);
kv.get(“foo”, 4); // 输出 “bar2”
kv.get(“foo”, 5); // 输出 “bar2”

代码

    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) {

            if(!map.containsKey(key))
                map.put(key,new TreeMap<>());
            map.get(key).put(timestamp,value);//存储key ->(timestamp->value)
        }
        public String get(String key, int timestamp) {

               if( map.get(key).floorEntry(timestamp)==null) return "";//没有小于或等于目标的key
             return  map.get(key).floorEntry(timestamp).getValue();
       
        }
    }

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值