题目传送: ​​https://leetcode.cn/problems/lru-cache/​

运行效率

Leetcode146. LRU 缓存_java


代码如下:

class LRUCache extends LinkedHashMap<Integer, Integer>{
private int capacity;

public LRUCache(int capacity) {
//LinkedHashMap有五个构造器:但是可以把accessOrDER 改成true的,只有
// LinkedHashMap(int initialCapacity,float loadFactor, boolean accessOrder) 这个构造器
// 所以负载因子必须要写,而要写负载因子,0.75比较合适,所以就是这样
super(capacity, 0.75F, true);
this.capacity = capacity;
}

public int get(int key) {
return super.getOrDefault(key, -1);
}

public void put(int key, int value) {
super.put(key, value);
}

@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}



/**
* 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);
*/