题目:
解答:java集合类中LinkedHashMap是基于哈希链表结构的,刚好用来实现LRU缓存很方便。
class LRUCache {
private int capacity;
Map<Integer,Integer> map;
//构造函数
public LRUCache(int capacity) {
this.capacity=capacity;
map=new LinkedHashMap<>(); //哈希链表结构
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
//把原来的数据删掉 在加到哈希链表前面来
Integer value = map.remove(key);
map.put(key, value);
return value;
}
public void put(int key, int value) {
//先看看原来的key存不存在,存在就先删掉在put进去
if (map.containsKey(key)) {
map.remove(key);
map.put(key, value);
return;
}
map.put(key, value);
//put的过程中如果超过了容量,就删掉第一个元素
if (map.size() > capacity) {
map.remove(map.entrySet().iterator().next().getKey());
}
}
}
/**
* 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);
*/