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算法,也就是系统中的页面最近最少使用算法,将最近最少使用的页面置换出去。那么在java中,其实是采用一个LinkedHashMap来实现的,既可以保证输入的顺序是按照插入的顺序,又可以保证在删除的时候是O(1)的时间复杂度。因为LinkedHashMap是一个双向链表来存储的。
class Node //定义一个Node类,有一个指向前一个节点的pre和指向后一个节点的next
{
int key;
int value;
Node pre;
Node next;
public Node(int key,int value)
{
this.key = key;
this.value = value;
}
}
public class LRUCache
{
int capacity; //hashMap的默认容量
Map<Integer,Node> hashMap = new HashMap<Integer,Node>(); //hashMap的结构,用一个Integer表示key值
Node head = null;
Node end = null;
public LRUCache(int capacity)
{
this.capacity = capacity;
}
public void remove(Node n)
{
if(n.pre != null) //因为这里保证了在hashMap中的每个node的key是不一样的,所以就可以直接找到
{
n.pre.next = n.next;
}
else
head = n.next;
if(n.next != null)
n.next.pre = n.pre;
else
end = n.pre;
}
public void setHead(Node n) //每次原来的页面重新被访问后,又将放到双向链表的头位置
{
n.next = head;
n.pre = null;
if(head != null)
head.pre = n;
head = n;
if(end == null)
end = head;
}
public int get(int key)
{
if(hashMap.containsKey(key))
{
Node n = hashMap.get(key);
remove(n);
setHead(n);
return n.value;
}
return -1;
}
public void set(int key,int value)
{
if(hashMap.containsKey(key))
{
Node old = hashMap.get(key);
old.value = value;
remove(old);
setHead(old);
}
else
{
Node created = new Node(key,value);
if(hashMap.size() >= capacity)
{
hashMap.remove(end.key);
remove(end);
setHead(created);
}
else
setHead(created);
hashMap.put(key, created);
}
}
}
此题阿里面试的时候又被问到,而在LeetCode居然有这题,说来也巧合,如果做过这题再去面阿里,估计就妥妥的了。