[编程题] lk [面试题 16.25. LRU缓存]
[编程题] lk 面试题 16.25. LRU缓存
基础
LRU:
![image-20200801150626694]([编程题] lk [股票类买卖问题(多个情况)--动态规划问题的综合提升].assets/image-20200801150626694.png)
LFU:
![image-20200801150845474]([编程题] lk [股票类买卖问题(多个情况)--动态规划问题的综合提升].assets/image-20200801150845474.png)
题目
![image-20200801155241592]([编程题] lk [股票类买卖问题(多个情况)--动态规划问题的综合提升].assets/image-20200801155241592.png)
输入输出
![image-20200801155259450]([编程题] lk [股票类买卖问题(多个情况)--动态规划问题的综合提升].assets/image-20200801155259450.png)
代码
import java.util.*;
class LRUCache {
int capacity;
LinkedHashMap<Integer,Integer> map;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new LinkedHashMap<>();
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;//不存在
}else{
//先删除再放到最后
Integer value = map.remove(key); //删除旧的位置是会返回删除结果的
map.put(key, value); //放入到最新的位置
return value;
}
}
public void put(int key, int value) {
if(map.containsKey(key)){
//先移除,再放最后
Integer values = map.remove(key);
map.put(key, value);
return;
}
//先判断是否已满,如果满就把map的size大于容量了就去掉头
if(map.size()>= capacity){
map.remove(map.keySet().iterator().next());
}
//再次加入,
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);
*/