981. 基于时间的键值存储-每日一题

一、题目

  创建一个基于时间的键值存储类 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)HashMap+TreeMap

  善于使用数据结构可以快速解题,使用HashMap的特性,可以快速找到key对应的entry,由于要找到小于等于给定timestampvalue,使用TreeMap的特性可以快速找到

三、代码

1)HashMap+TreeMap

class TimeMap {
    private Map<String, TreeMap<Integer, String>> map;
    public TimeMap() {
        map = new HashMap<String, TreeMap<Integer, String>>();
    }
    
    public void set(String key, String value, int timestamp) {
        // if (!map.containsKey(key)) {
        //     map.put(key, new TreeMap<Integer, String>());
        // }
        // map.get(key).put(timestamp, value);	// 可化简为下面一行
        map.computeIfAbsent(key, k -> new TreeMap<Integer, String>()).put(timestamp, value);
    }
    
    public String get(String key, int timestamp) {
        if (!map.containsKey(key)) {
            return "";
        }
        Map.Entry<Integer, String> entry = map.get(key).floorEntry(timestamp);
        if (entry == null) {
            return "";
        }
        return entry.getValue();
    }

  时间复杂度为O(nlogC)C是单个key中不同值的数量,空间复杂度为O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

佳鑫大大

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值