-
题目:460. LFU Cache
设计并实现最不经常使用(LFU)缓存的数据结构。它应该支持以下操作:get 和 put。get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。
put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前,使最不经常使用的项目无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,最近最少使用的键将被去除。 -
进阶:
你是否可以在 O(1) 时间复杂度内执行两项操作? -
示例:
LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 去除 key 2
cache.get(2); // 返回 -1 (未找到key 2)
cache.get(3); // 返回 3
cache.put(4, 4); // 去除 key 1
cache.get(1); // 返回 -1 (未找到 key 1)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
- Code
//460. LFU Cache
public class LFUCache {
//保存key,value
HashMap<Integer,Integer> vals;
//保存key对应value的访问次数
HashMap<Integer,Integer> counts;
//保存相同访问次数的key的set集合
HashMap<Integer,LinkedHashSet<Integer>> lists;
int cap;
//初始化数据出现的频次
int min=-1;
public LFUCache(int capacity) {
cap=capacity;
vals=new HashMap<>();
counts=new HashMap<>();
lists=new HashMap<>();
}
public int get(int key) {
if(!vals.containsKey(key))
return -1;
int count=counts.get(key);
counts.put(key,count+1);
lists.get(count).remove(key);
//判断min要不要加1
if(count==min&&lists.get(count).size()==0){
min++;
}
if(!lists.containsKey(count+1)){
lists.put(count+1,new LinkedHashSet<>());
}
lists.get(count+1).add(key);
return vals.get(key);
}
public void put(int key, int value) {
if(cap<=0)
return;
if(vals.containsKey(key)){
vals.put(key,value);
get(key);
return;
}
if(vals.size()>=cap){
int minFreKey=lists.get(min).iterator().next();
lists.get(min).remove(minFreKey);
vals.remove(minFreKey);
counts.remove(minFreKey);
}
vals.put(key,value);
counts.put(key,1);
min=1;
if(!lists.containsKey(1)){
lists.put(1,new LinkedHashSet<>());
}
lists.get(1).add(key);
}
}