美文网首页
LeetCode 第 981 题:基于时间的键值存储

LeetCode 第 981 题:基于时间的键值存储

作者: 放开那个BUG | 来源:发表于2023-02-19 23:22 被阅读0次

1、前言

题目描述

2、思路

这道题基本思路是两个 map,第一个是普通的 hashmap,key 为 set 的 key,value 为一个 treemap,treemap 的 key 为 timestamp,value 是要 set 的 value。但从耗时看,貌似 value 为 treemap 的耗时长。所以 value 还可以是数组,然后使用二分查找寻找数组中的元素。

3、代码

class TimeMap {

    private Map<String, TreeMap<Integer, String>> map = new HashMap<>();

    public TimeMap() {

    }
    
    public void set(String key, String value, int timestamp) {
        if(map.get(key) == null){
            map.put(key, new TreeMap<>());
        }
        TreeMap<Integer, String> store = map.get(key);
        store.put(timestamp, value);
    }
    
    public String get(String key, int timestamp) {
        if(map.get(key) == null){
            return "";
        }
        TreeMap<Integer, String> store = map.get(key);
        Map.Entry<Integer, String> sub = store.floorEntry(timestamp);
        if(sub == null){
            return "";
        }
        return sub.getValue();
    }
}

相关文章

网友评论

      本文标题:LeetCode 第 981 题:基于时间的键值存储

      本文链接:https://www.haomeiwen.com/subject/psahyrtx.html