1 LUR缓存
/**
核心思路:使用LinkedHashMap,保持插入的顺序
*/
class LRUCache {
//1)定义最大值和map集合
private int capacity;
private Map<Integer,Integer> map=new LinkedHashMap<>();
//2)书写方法:复制容量最大
public LRUCache(int capacity) {
this.capacity=capacity;
}
//书写方法:获取值,需要放到最后面
public int get(int key) {
if(map.keySet().contains(key)){
int value=map.get(key);
map.remove(key);
map.put(key,value);
return value;
}else{
return -1; //查询失败
}
}
//书写方法:之前就存在,则先删除再添加;之前不存在,则先去除第一个再添加(第一个为最少使用)
public void put(int key, int value) {
if(map.keySet().contains(key)){
map.remove(key);
}else{
if(map.size()==capacity){
//通过迭代器遍历map集合,并且删除第一个元素
Iterator<Map.Entry<Integer,Integer>> iterator=map.entrySet().iterator();
iterator.next();
iterator.remove();
}
}
map.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);
*/