/**
* 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);
*/
class LRUCache {
Map<Integer,Integer> map ;
Stack<Integer> stack;
int size;
public LRUCache(int capacity) {
stack = new Stack<>();
map = new HashMap<>(capacity);
size = capacity;
}
public int get(int key) {
if(!stack.contains(key)){
return -1;
}
boolean flag = stack.remove(Integer.valueOf(key));
stack.push(key);
return map.get(key);
}
public void put(int key, int value) {
if(stack.contains(key)){
stack.remove(Integer.valueOf(key));
}else{
if(stack.size() == size){
int count = stack.remove(0);
map.remove(count);
}
}
stack.push(key);
map.put(key,value);
}
}
java 实现LRU(最近最少使用)缓存机制
猜你喜欢
转载自blog.csdn.net/u013045878/article/details/81316452
今日推荐
周排行