39 lines
823 B
Java
39 lines
823 B
Java
/*
|
|
* @lc app=leetcode id=146 lang=java
|
|
*
|
|
* [146] LRU Cache
|
|
*/
|
|
|
|
// @lc code=start
|
|
class LRUCache {
|
|
private LinkedHashMap<Integer, Integer> cache;
|
|
private int cap;
|
|
|
|
public LRUCache(int capacity) {
|
|
this.cap = capacity;
|
|
cache = new LinkedHashMap<>(capacity, 0.75f, true) {
|
|
@Override
|
|
protected boolean removeEldestEntry(Map.Entry eldest) {
|
|
return this.size() > cap;
|
|
}
|
|
};
|
|
}
|
|
|
|
public int get(int key) {
|
|
return cache.getOrDefault(key, -1);
|
|
}
|
|
|
|
public void put(int key, int value) {
|
|
cache.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);
|
|
*/
|
|
// @lc code=end
|
|
|