LRU 缓存
作者:
Jiarui1111
,
2023-09-19 13:58:45
,
所有人可见
,
阅读 98
class LRUCache {
int cap;
Map<Integer, Integer> map = new LinkedHashMap<>();
public LRUCache(int capacity) {
this.cap = capacity;
}
public int get(int key) {
if(map.containsKey(key)) {
int val = map.get(key);
map.remove(key);
map.put(key, val);
return val;
}
return -1;
}
public void put(int key, int value) {
if(map.containsKey(key)) {
map.remove(key);
}else if(map.size() == cap) {
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
iterator.next();
iterator.remove();
}
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);
*/