-实现 LFU 缓存算法

2021-07-03 11:06

阅读:558

标签:integer   values   set   put   iterator   oid   remove   dha   void   

-实现 LFU 缓存算法, 设计一个类 LFUCache,实现下面三个函数
+ 构造函数: 传入 Cache 内最多能存储的 key 的数量
+ get(key):如果 Cache 中存在该 key,则返回对应的 value 值,否则,返回-1。
+ set(key,value):如果 Cache 中存在该 key,则重置 value 值;如果不存在该 key,则将该 key 插入到到 Cache 中,若插入后会导致 Cache 中存储的 key 个数超过最大容量,则在插入前淘汰访问次数最少的数据。

注:
所有 key 和 value 都是 int 类型。
访问次数:每次get/set一个存在的key都算作对该key的一次访问;当某个key被淘汰的时候,访问次数清零。


public class LFUCache{
HashMap keyValues;
HashMap keyCounts;
HashMap> countKeySets;

int capacity;
int min;

public LFUCache(int capacity){
this.capacity = capacity;
this.min = -1;
keyValues = new HashMap();
keyCounts = new HashMap();
countKeySets = new HashMap>;
countKeySets.put(1,LinkedHashSet());
}

public int get(int key){
if(!keyValues.containsKey(key)){
return -1;
}
int count = KeyCounts.get(key);
keyCounts.put(key,count+1);
countKeySets.get(count).remove(key);
if(count == min && countKeySets.get(count).size() == 0){
min++;
}
if(!countKeySets.containsKey(count+1){
countKeySets.put(count+1,new LinkedHashSet());
}
countKeySets.get(count+1).add(key);
return keyValues.get(key);
}

public void set(int key , int value){
if(capacity return ;
}

if(keyValues.containsKey(key)){
keyValues.put(key,value);
get(key);
return;
}
if(keyValues.size() >= capacity){
int leastFreq = countKeySets.get(min).iterator().next();
keyValues.remove(lestFreq);
keyCounts.remove(lestFreq);
countKeySets.get(min).remove(leastFreq);
}

keyValues.put(key,value);
keyCounts.put(key,1);
countKeySets.get(1).add(key);
min = 1;
}


}

-实现 LFU 缓存算法

标签:integer   values   set   put   iterator   oid   remove   dha   void   

原文地址:https://www.cnblogs.com/canacezhang/p/9622788.html


评论


亲,登录后才可以留言!