首页 > 编程语言 > 详细

-实现 LFU 缓存算法

时间:2018-09-10 21:05:51      阅读:206      评论:0      收藏:0      [点我收藏+]

-实现 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<Integer,Integer> keyValues;
HashMap<Integer,Integer> keyCounts;
HashMap<Integer,LinkedHashSet<Integer>> countKeySets;

int capacity;
int min;

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

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<Integer>());
}
countKeySets.get(count+1).add(key);
return keyValues.get(key);
}

public void set(int key , int value){
if(capacity <= 0){
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 缓存算法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!