题解 | #设计LRU缓存结构#TOP100
其实按道理,应该自己写一个,LRU原则就是最近最少使用,每次添加的时候,将最少使用的删除掉。使用一次就放到栈顶,移除的时候就是移除栈底。或者使用一次放到队头,移除的时候就是移除队尾
import java.util.*;
public class Solution {
Map<Integer, Integer> map;
int capacity;
public Solution(int capacity) {
// write code here
this.capacity = capacity;
map = new LinkedHashMap<Integer,Integer>(capacity, 0.75f,true){
@Override
protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest){
return super.size() > capacity;
}
};
}
public int get(int key) {
// write code here
if(!map.containsKey(key)){
return -1;
}
return map.get(key);
}
public void set(int key, int value) {
// write code here
map.put(key, value);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution solution = new Solution(capacity);
* int output = solution.get(key);
* solution.set(key,value);
*/