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.
Input:
2,[get(2),set(2,6),get(1),set(1,5),set(1,2),get(1),get(2)]
Output:
[-1,-1,2,6]
实现代码如下:
public class LRUCache {
private int capacity;
private HashMap<Integer,Node> hashMap = new HashMap<>();
private Node head = new Node(-1,-1);
private Node tail = new Node(-1,-1);
private class Node {
Node pre;
Node next;
int key;
int value;
Node(int key,int value) {
this.key = key;
this.value = value;
}
}
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if(!hashMap.containsKey(key)) {
return -1;
}
moveToHead(key);
return hashMap.get(key).value;
}
public void set(int key, int value) {
if(get(key) != -1) {
hashMap.get(key).value = value;
moveToHead(key);
return;
}
if(hashMap.size() == capacity) {
removeFromTail();
}
Node node = new Node(key,value);
node.value = value;
hashMap.put(key,node);
node.next = head.next;
head.next.pre = node;
node.pre = head;
head.next = node;
}
public void moveToHead(int key) {
Node temp = hashMap.get(key);
temp.pre.next = temp.next;
temp.next.pre = temp.pre;
temp.next = head.next;
head.next.pre = temp;
head.next = temp;
temp.pre = head;
}
public void removeFromTail() {
hashMap.remove(tail.pre.key);
tail.pre.pre.next = tail;
tail.pre = tail.pre.pre;
}
}
稍微说明下。
用HashMap可以快速判断链表中是否有要查找的节点以及要放入的节点在链表中是否已存在(是的话只要更新下值就行了)。
设置头尾指针是因为LRU算法中要频繁用到将某节点插入或移到头部,或从尾部移除某个元素。
用双向链表主要是为了操作时的效率,这样每次用HashMap找到相应节点后,直接在节点上操作就行了,没必要每次遍历到这个节点的前一个节点,然后再进行操作。