Description
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.
- Could you do both operations in O(1) time complexity?
思路分析
LRU是操作系统虚拟内存的页面置换算法的一种。含虚拟内存的系统,当进程发生缺页,需要从SWAP(交换区)中换入所需的页到内存块中,此时内存却已满,需要将一个页面换出到SWAP中,选择这个换出页面的算法就是页面置换算法。
最理想的算法是,其选择的被淘汰的页面将是以后永久不使用的,或许是在最长(未来)时间内不再被访问的页面,采用这种算法可以获得最低的缺页率,但目前还无法预知,此算法无法实现,但可以利用该算法去评价其他算法。
FIFO算法是最早出现的算法,即系一个队列存储换入页面,该算法淘汰最先进入内存的页面,也就是在内存中驻留时间最久的页面。不符合程序运行的规律,因为页面调入的先后并不能反应页面的使用情况。
LRU(Least Recently Used)最近最久未使用算法,其根据页面调入内存后的使用情况做出决策的,无法预知未来,以“最近的过去”和“最近的未来”近似,LRU置换算法是选择最近最久未被使用的页面予以淘汰。
方案
哈希表能实现O(1)的get操作,但无法记录使用状况,用一个字段去记录并不是很实际,使用频率高的页面该数值可能很大。使用数组存储的话,移动一个元素可能要O(n)时间,因此用链表结构表示,最近使用的节点通通添加到链表末尾,那么在链表头部就是最近最久未使用的节点,在恰当的时机可将其淘汰。由于需要快速访问链表尾部和链表头部,可以建立一个双向链表,为了快速访问节点,可以在双向链表上建立哈希表。get和put操作都可以保证O(1)时间。
java中有一个这样的集合类型,LinkedHashMap.
代码
方案一
HashMap+Doubly-linkdedList
在双向链表中保存两个位置固定但内容却为空的的节点当尾节点和头节点,这样各项操作写起来比较简洁。
public class LRUCache {
class Node{
Integer key;
Integer value;
Node pre;//
Node next;// doubly-linkedlist
Node(Integer key,Integer value){
this.key=key;
this.value=value;
}
}
/**build hash on the doubly-linkedlist, make sure we do both operation in O(1) time complexity **/
/**some field**/
private int capacity;//the capacity of LRUCache
private int n;//represent the current node numbers, origin will be zero
private HashMap<Integer,Node> map;
private Node head;//doubly-linkedlist, the reference to the head
private Node tail;//the reference to the tails
public LRUCache(int capacity) {
this.capacity=capacity;
this.n=0;
head=new Node(null,null);
tail=new Node(null,null);
//dont put anything to these two node,they are always exist.
tail.pre=head;
head.next=tail;
map=new HashMap<Integer,Node>();
}
public int get(int key) {
if(map.get(key)!=null){
Node node=map.get(key);//if key is already exist
//update the linkedlist
node.pre.next=node.next;
node.next.pre=node.pre;
appendTail(node);
return node.value;//return value;
}
return -1;
}
public void put(int key, int value) {
if(get(key)!=-1){//put the node to the tail
Node node=map.get(key);//if key is already exist
node.value=value;//update the value,
}else{//else insert a Node
n++; //curent node number incre
if(n>capacity){
Node tmp=head.next;
// got to be remove the eldest after which is the head
head.next=head.next.next;
head.next.pre=head;
map.remove(tmp.key);
n--;//size decre
}
Node tmp=new Node(key,value);
map.put(key,tmp);//update the hashMap
appendTail(tmp);//insert a node to the tails
}
}
/**append the node before the tail of doubly-linkedlist**/
private void appendTail(Node node){
node.next=tail;
node.pre=tail.pre;
tail.pre.next=node;
tail.pre=node;
}//appendTail
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
方案二
使用java.util.LinkedHashMap
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html
重写一个方法removeEldestEntry,告知淘汰最老的节点的规则。
cache=new LinkedHashMap
public class LRUCache {
private LinkedHashMap<Integer,Integer> cache;
private int maxCap;
public LRUCache(int capacity) {
maxCap=capacity;
cache=new LinkedHashMap<Integer,Integer>(capacity,0.75f,true){
//override
protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest) {
return cache.size()>maxCap;
}
};
}
public int get(int key) {
if(cache.containsKey(key)){
return cache.get(key);
}
return -1;
}
public void put(int key, int value) {
cache.put(key,value);
}
}