手撕LRU
解题思路
- LinkedList储存key值,实现最近最少使用。
- get:如果存在该key,则先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,越最近使用的key越靠近LinkedList末尾。
- put:如果存在该key,也要像get一样,先把LinkedList中原来的key值删除,再把key添加到LinkedList末尾,直接调用HashMap的put方法,新的value值就会覆盖旧的value值。
- 如果put之前元素个数已经达到了容量,则把LinkedList中第一个元素删除,越是最近最少使用的key越靠近LinkedList头部。然后调用HashMap的put方法。
- 不存在该key,也没有到达容量,直接调用HashMap的put方法。
class LRUCache {
private int capacity;
private HashMap<Integer,Integer> map;
private LinkedList<Integer> list;
public LRUCache(int capacity) {
this.capacity=capacity;
map=new HashMap<>();
list=new LinkedList<>();
}
public int get(int key) {
if(map.containsKey(key)){
list.remove((Integer)key);
list.addLast(key);
return map.get(key);
}
return -1;
}
public void put(int key, int value) {
if(map.containsKey(key)){
list.remove((Integer)key);
list.addLast(key);
map.put(key,value);
return;
}
if(list.size()==capacity){
map.remove(list.removeFirst());
map.put(key,value);
list.addLast(key);
}
else{
map.put(key,value);
list.addLast(key);
}
}
}
import java.util.LinkedHashMap;
import java.util.Map;
public class LRU {
class LRUCache extends LinkedHashMap<Integer, Integer> {
private int capacity; //最多能缓存多少数据
public LRUCache(int capacity) {
//设置初始大小,负载因子
//true指的是让LinkedHashMap按照访问顺序来进行排序,最近访问的放在头,最老访问的放在尾
super(capacity, 0.75F, true);
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
// 当map中的数据量大于指定的缓存个数时,就自动删除最老的数据
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
}

本文详细介绍了如何实现LRU(最近最少使用)缓存算法。通过结合使用HashMap和LinkedList,或者使用LinkedHashMap,实现了高效的键值对存储和访问策略。在get和put操作中,确保了最近使用的项被置于数据结构的末端,而当达到缓存容量限制时,会自动移除最久未使用的项。
5484

被折叠的 条评论
为什么被折叠?



