解题思路:
用map来记录数据
用list数组更新数据的使用情况
提交代码:
class LRUCache {
Map<Integer,Integer> map=new HashMap<>();
List<Integer> history=new ArrayList<>();
int cap;
public LRUCache(int capacity) {
this.cap=capacity;
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
history.remove((Integer)key);
history.add(key);
return map.get((Integer)key);
}
public void put(int key, int value) {
if(map.containsKey(key)) {
map.put(key, value);
history.remove((Integer)key);
history.add(key);
}
else if(history.size()==cap) {
int p=history.remove(0);
map.remove(p);
history.add(key);
map.put(key, value);
}else {
history.add(key);
map.put(key, value);
}
}
}
运行结果:

本文介绍了一种使用HashMap和ArrayList实现LRU(Least Recently Used)缓存策略的方法。通过维护一个键值对映射和一个访问历史列表,确保最近最少使用的数据在达到容量限制时被移除,以保持缓存的高效运作。
1820

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



