class LRUCache {
int capacity;
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
// return map.getOrDefault(key, -1); API自带的返回默认值并且将位置调整至链表尾部的方法
if (!map.containsKey(key)) {
return -1;
}
// 将 key 变为最近使用的
makeNearest(key);
return map.get(key);
}
public void put(int key, int value) {
if (map.containsKey(key)) {
// 修改 key 对应的值
map.put(key, value);
// 将 key 变为最近使用的
makeNearest(key);
return;
}
if (map.size() >= this.capacity) {
// 链表头部为最久未使用的 key
int oldestKey = map.keySet().iterator().next();
map.remove(oldestKey);
}
// 将新的 key 添加链表尾部
map.put(key, value);
}
private void makeNearest(int key) {
int value = map.get(key);
// 删除 key,从新添加到链表尾部
map.remove(key);
map.put(key, value);
}
}
/**
* 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);
*/