LeetCode146-LRU缓存机制
题目
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
解法
方法一:自己实现一个Map和双向链表的方法
class LRUCache {
Map<Integer,DoubleNode> map = new HashMap<>();
int n ;
int len;
DoubleNode dummy = new DoubleNode(0,0);
DoubleNode tail = dummy;
public LRUCache(int capacity) {
n = capacity;
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
DoubleNode res = map.get(key);
if(res.next!=null){
res.pre.next = res.next;
res.next.pre = res.pre;
tail.next = res;
res.pre = tail;
tail = res;
tail.next = null;
}
return res.val;
}
public void put(int key, int value) {
if(map.containsKey(key)){
get(key);
tail.val = value;
}else{
DoubleNode cur = new DoubleNode(key,value);
if(len == n ){
DoubleNode temp = dummy.next;
map.remove(temp.key);
if(n==1){
dummy.next = null;
tail = dummy;
}
else{
//这里要注意不要写错了
DoubleNode c = dummy.next.next;
dummy.next = c;
c.pre = dummy;
}
}else{
++len;
}
map.put(key,cur);
tail.next = cur;
cur.pre = tail;
tail = tail.next;
}
}
//双向链表
class DoubleNode{
int key;
int val;
DoubleNode next;
DoubleNode pre;
public DoubleNode(){}
public DoubleNode(int x,int y){
key = x;
val = y;
}
}
}
方法二:
class LRUCache extends LinkedHashMap<Integer, Integer>{
private int capacity;
public LRUCache(int capacity) {
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);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}