码迷,mamicode.com
首页 > 编程语言 > 详细

-实现 LFU 缓存算法

时间:2018-09-10 21:22:18      阅读:225      评论:0      收藏:0      [点我收藏+]

标签: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<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 缓存算法

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!