用哈希表 key → (value, expireAt) 模拟 TTL 缓存。
now 满足 now >= expireAt 即过期。get 遇过期返回 -1,但不删除条目(仍占容量)。|map| > capacity,按 (expireAt, key) 字典序最小淘汰一条(过期最早,其次键更小)。不顺带清理其它过期键。请实现一个带容量上限和过期时间的缓存。
capacity:最多同时存放多少个不同的键expireAt在时刻 now 判断是否过期的规则是:若 now≥expireAt,则该键已过期(expireAt 表示「从这个时刻起失效」)。
注意:过期键在调用 purge 之前仍占容量;get 遇到过期键只返回 -1,不会自动删除。
TTLCache(int capacity):初始化空缓存(保证 capacity≥1)put(int key, int value, int expireAt):写入或覆盖该键的值与过期时刻
capacity:淘汰一个键——优先淘汰 expireAt 最小者;若并列,淘汰 key 更小者get(int key, int now):
-1purge(int now):删除所有满足 now≥expireAt 的键,返回删除个数size():返回当前存放的键数量(包含已过期但尚未 purge 的键)每行一次函数调用。首行 TTLCache(capacity)。累计调用不超过 4000 次。
put 返回 nullget / purge / size 返回整数输入:
TTLCache(2)
put(1, 10, 5)
put(2, 20, 3)
get(2, 2)
get(2, 3)
put(3, 30, 4)
get(1, 0)
size()
purge(4)
size()
get(3, 4)
输出:
null
null
null
20
-1
null
10
2
1
1
-1
说明:
put(1,10,5)、put(2,20,3):缓存满 2 个键get(2,2):未过期,返回 20get(2,3):3≥3 已过期,返回 -1,但键 2 仍占位put(3,30,4):超容量,按过期时刻淘汰最早的键 2(expireAt=3),留下 {1,3}get(1,0) 仍命中;size()=2purge(4):删去已过期的 3(4≥4),返回 1;剩键 1,size()=1get(3,4):键已不存在,返回 -1
By signing up a CodeFun2000 universal account, you can submit code and join discussions in all online judging services provided by us.