Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
题解:用双向链表实现一个LRU cache,这里自定义越靠近链表头的node,在越近的时间使用过。支持两个操作——get和set:
- get(key):如果链表中有key对应的node,返回该node的值,并把node移到链表头部(最近使用过);如果没有,返回-1;
- set(key,value):如果链表中已经有key对应的node,修改对应node的值为value(但不需要把这个node放在头结点处);如果链表中没有key对应的node,那么要新建node插入链表中,但此时要看链表是否还有空间。如果没有,就将尾部node(最少使用的node)删除,然后在头部插入新的node。
为了提高查找效率,这里使用一个hashMap存放<key,node>键值对,这样就可以在O(1)的时间判断cache中是否存在对应的key。
代码如下:
public class LRUCache {
private class Node{
int value;
int key;
Node before;
Node after;
public Node(int key,int value){
this.value = value;
this.key = key;
before = null;
after = null;
}
} private int capacity;
private HashMap<Integer, Node> map = new HashMap<Integer,Node>();
private Node headNode = new Node(-1, -1);
private Node tailNode = new Node(-1, -1); public LRUCache(int capacity) {
this.capacity = capacity;
headNode.after = tailNode;
tailNode.before = headNode;
} public void move_to_head(Node current){
current.after = headNode.after;
headNode.after = current;
current.before = headNode;
current.after.before = current;
}
public int get(int key) {
//if we don't have this node
if(!map.containsKey(key))
return -1; //if we have this node, get it and move it to head
Node current = map.get(key);
current.before.after = current.after;
current.after.before = current.before;
move_to_head(current); return map.get(key).value;
} public void set(int key, int value) {
//if we already have this node,just change its value
if(get(key) != -1){
map.get(key).value = value;
return;
} //if we indeed don't have this node, we first check capacity
if(map.size() == capacity){
map.remove(tailNode.before.key);
tailNode.before.before.after = tailNode;
tailNode.before = tailNode.before.before;
} //now we are sure we have space for this new node,put it ahead of the list
Node newNode = new Node(key, value);
map.put(key, newNode);
move_to_head(newNode);
}
}
在实现的时候,还设置了两个node:head和tail,真正的cache数据节点存放在二者之间。