public class LRUCache {
int cap;
LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<>();
LRUCache(int cap){
this.cap = cap;
}
public int get(int key) {
if (!linkedHashMap.containsKey(key)) {
return -1;
}
makeUse(key);
return linkedHashMap.get(key);
}
public void put(int key, int val) {
if (linkedHashMap.containsKey(key)) {
linkedHashMap.put(key, val);
makeUse(key);
return;
}
if (linkedHashMap.size() >= cap) {
Integer next = linkedHashMap.keySet().iterator().next();
linkedHashMap.remove(next);
}
linkedHashMap.put(key, val);
}
public void makeUse(int key) {
//删除key
Integer remove = linkedHashMap.remove(key);
linkedHashMap.put(key, remove);
}
}
public class LRUCache { int cap; LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>(); public LRUCache(int capacity) { this.cap = capacity; } public int get(int key) { if (!cache.containsKey(key)) { return -1; } // 将 key 变为最近使用 makeRecently(key); return cache.get(key); } public void put(int key, int val) { if (cache.containsKey(key)) { // 修改 key 的值 cache.put(key, val); // 将 key 变为最近使用 makeRecently(key); return; } if (cache.size() >= this.cap) { // 链表头部就是最久未使用的 key int oldestKey = cache.keySet().iterator().next(); cache.remove(oldestKey); } // 将新的 key 添加链表尾部 cache.put(key, val); } private void makeRecently(int key) { int val = cache.get(key); // 删除 key,重新插入到队尾 cache.remove(key); cache.put(key, val); }}
标签:val,实现,cache,List,int,LRU,key,public,linkedHashMap
From: https://www.cnblogs.com/jichenghui/p/18359068