代码拉取完成,页面将自动刷新
import java.util.HashMap;
import java.util.LinkedHashMap;
/*
* @lc app=leetcode.cn id=146 lang=java
*
* [146] LRU 缓存机制
*/
// @lc code=start
class LRUCache {
private LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();
private int cap;
public LRUCache(int capacity) {
cap = capacity;
}
public int get(int key) {
if (!cache.containsKey(key)) {
return -1;
}
makeRecently(key);
return cache.get(key);
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
cache.put(key, value);
makeRecently(key);
return;
}
if (cap == cache.size()) {
int oldestKey = cache.keySet().iterator().next();
cache.remove(oldestKey);
}
cache.put(key, value);
}
public void makeRecently(int key) {
int val = cache.get(key);
cache.remove(key);
cache.put(key, val);
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
// @lc code=end
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。