Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
思想:
这道题要求设计实现LRU cache的数据结构,实现set和get功能。学习过操作系统的都应该知道,cache作为缓存可以帮助快速存取数据,但是确定是容量较小。这道题要求实现的cache类型是LRU,LRU的基本思想就是“最近用到的数据被重用的概率比较早用到的大的多”,是一种更加高效的cache类型。
“为了能够快速删除最久没有访问的数据项和插入最新的数据项,我们将双向链表连接Cache中的数据项,并且保证链表维持数据项从最近访问到最旧访问的顺序。 每次数据项被查询到时,都将此数据项移动到链表尾部(O(1)的时间复杂度)。这样,在进行过多次查找操作后,最近被使用过的内容就向链表的尾部移动,而没有被使用的内容就向链表的前面移动。当需要替换时,链表最前面的位置就是最近最少被使用的数据项,我们只需要将最新的数据项放在链表尾部,当Cache满 时,淘汰链表最前的位置就是了。 ”
解决了LRU的特性,现在考虑下算法的时间复杂度。为了能减少整个数据结构的时间复杂度,就要减少查找的时间复杂度,所以这里利用HashMap来做,这样时间复杂度就是O(1)。
方法:
get(key): 如果cache中不存在要get的值,返回-1;如果cache中存在要找的值,返回其值并将其在原链表中删除,然后将其移动到最尾端。
set(key,value):
- 调用get方法看返回不返回-1,当不返回-1也就是已经存在时,更新其value,调用的get方法会自动将其放在尾端;
- 当这个值不存在时,如果map.size()==capacity,也就是当前map容量已满,如要删除前面(head.next)点,然后将此点put进来;
class LRUCache {
private class Node{
Node pre;
Node next;
int key;
int value;
public Node(int key,int value){
this.key=key;
this.value=value;
this.pre=null;
this.next=null;
}
}
private int capacity;
private Node head=new Node (-1,-1);
private Node tail=new Node(-1,-1);
private HashMap<Integer,Node> map=new HashMap<Integer,Node>();
public LRUCache(int capacity) {
this.capacity=capacity;
tail.pre=head;
head.next=tail;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
Node n=map.get(key);
remove(n);
toTail(n);
//因为返回的是int值
return n.value;
}
public void put(int key, int value) {
//如果这个值存在,更新value,return
//get函数已经有了movetoTail
if (get(key) != -1) {
map.get(key).value = value;
return;
}
//如果没有存在
//如果现在map已经存满,remove最靠前的点
if(map.size()==capacity){
map.remove(head.next.key);
head.next=head.next.next;
head.next.pre=head;
}
Node n=new Node(key,value);
map.put(key,n);
toTail(n);
}
private void toTail(Node n){
n.pre=tail.pre;
tail.pre=n;
n.pre.next=n;
n.next=tail;
}
private void remove(Node n){
n.pre.next=n.next;
n.next.pre=n.pre;
}
}
Some tips:
- 主要数据结构 hashmap<integer,node>
doublelinkedlist - (node).val 返回整型
- hashmap存放 map.put()
删除 map.remove()