思路:删除继承类
// @Title: LRU 缓存 (LRU Cache)
// @Author: qisiii
// @Date: 2022-02-22 12:12:33
// @Runtime: 42 ms
// @Memory: 108 MB
// @comment: 删除继承类
// @flag: ORANGE
class LRUCache{
private int capacity;
private LinkedHashMap<Integer,Integer> cache;
public LRUCache(int capacity) {
cache=new LinkedHashMap(capacity,0.75f,true){
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return cache.size()>capacity;
};
};
this.capacity=capacity;
}
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);
*/
思路:
// @Title: LRU 缓存 (LRU Cache)
// @Author: qisiii
// @Date: 2023-12-31 23:25:27
// @Runtime: 42 ms
// @Memory: 108.5 MB
// @comment:
// @flag:
public class LRUCache {
private LinkedHashMap<Integer,Integer> linkedHashMap;
public LRUCache(int capacity) {
linkedHashMap=new LinkedHashMap<Integer,Integer>(capacity,0.75f,true){
@Override
protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest){
return size()>capacity;
}
};
}
public int get(int key) {
return linkedHashMap.getOrDefault(key, -1);
}
public void put(int key, int value) {
linkedHashMap.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);
*/
思路:使用linkedhashmap
// @Title: LRU 缓存 (LRU Cache)
// @Author: qisiii
// @Date: 2022-02-22 12:11:06
// @Runtime: 41 ms
// @Memory: 108.2 MB
// @comment: 使用linkedhashmap
// @flag: BLUE
class LRUCache extends LinkedHashMap{
private int capacity;
private LinkedHashMap<Integer,Integer> cache;
public LRUCache(int capacity) {
cache=new LinkedHashMap(capacity,0.75f,true){
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return cache.size()>capacity;
};
};
this.capacity=capacity;
}
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);
*/