update dp

This commit is contained in:
ranwenjie
2021-11-10 14:27:03 +08:00
parent b3672ec2f0
commit 5a0d23faa8
4 changed files with 87 additions and 2 deletions
+58
View File
@@ -100,6 +100,64 @@ protected boolean removeEldestEntry(Map.Entry eldest) {
```
基于 LinkedHashMap实现的 LRU Cache
```Java
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);
}
//添加元素到cache
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);
}
}
```