题目链接:https://leetcode.com/problems/lru-cache/
题目:
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.
解题思路:
1、用一个hash表来维护结点的位置关系,也就是hash表的key就是资源本身的key,value是资源的结点(包含key和value的信息)。
2、把结点维护成一个双向链表构成的队列,这样子如果我们要访问某一个结点,那么可以通过hash表和key来找到结点,从而取到相应的value。而当我们想要删除或者插入结点时,我们还是通过hash表找到结点,然后通过双向链表和队列的尾结点把自己删除同时插入到队尾。
3、通过hash表访问结点我们可以认为是O(1)的操作(假设hash函数足够好),然后双向链表的插入删除操作也是O(1)的操作。如此我们便实现了用O(1)时间来完成所有LRU cache的操作。空间上就是对于每一个资源有一个hash表的的项以及一个对应的结点(包含前后指针和资源的<key, value>
)。
参考链接:http://blog.csdn.net/linhuanmars/article/details/21310633
注意:
1、链表为空时,插入节点
2、删除的节点在头,在尾或者在中间
3、插入的节点若键已存在,则替换其值,再将其从链表中删除后插入链表末尾
public class LRUCache {
class Node {
int key;
int value;
Node next;
Node pre;
public Node(int k, int v) {
this.key = k;
this.value = v;
}
}
private HashMap<Integer, Node> map;
private int capacity;
private Node head, tail;
public LRUCache(int capacity) {
this.map = new HashMap<Integer, Node>();
this.capacity = capacity;
head = null;
tail = null;
}
public int get(int key) {
Node node = map.get(key);
if(node == null)
return -1;
if(node != tail) {
if(node == head)
head = head.next;
else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
return node.value;
}
public void set(int key, int value) {
Node node = map.get(key);
if(node != null) {
node.value = value;
if(node != tail) {
if(node == head)
head = head.next;
else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
} else {
Node newNode = new Node(key, value);
if(this.capacity == 0) {
Node temp = head;
head = head.next;
map.remove(temp.key);
this.capacity ++;
}
if(head == null && tail == null)
head = newNode;
else {
tail.next = newNode;
newNode.pre = tail;
newNode.next = null;
}
tail = newNode;
map.put(key, newNode);
this.capacity --;
}
}
}