问题:
解题:
分析:需要对最近使用的操作进行排序,需要判断缓存最大值,但是要注意若对一个值进行多次操作只能有一条记录;至少有一个链表用于存储对值的操作,方便去除队尾,有一个map对值进行操作,用于随机,LinkedHashMap是个不错的选择
class LRUCache {
private int maxSize;
private LinkedHashMap<Integer, Integer> hashMap;
public LRUCache(int capacity) {
this.maxSize = capacity;
this.hashMap = new LinkedHashMap<>(capacity);
}
public int get(int key) {
// 判断是否包含
if (!hashMap.containsKey(key)) {
return -1;
}
// 调用get的就要改变顺序
Integer value = hashMap.remove(key);
hashMap.put(key, value);
return value;
}
public void put(int key, int value) {
// 判断是否是已经包含的
if (hashMap.containsKey(key)) {
// 先从链表中移除
hashMap.remove(key);
// 判断是否已经到达临界值
} else if (hashMap.size() >= maxSize) {
Integer firstKey = hashMap.keySet().iterator().next();
hashMap.remove(firstKey);
}
// 添加到链表的末尾
hashMap.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);
*/
性能:
目前的get和put方法执行的步骤还是比较多的,比较慢