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.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
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
public class LRUCache {
int capacity;
int size;
HashMap<Integer,Node> map;
DLinkedList dlist;
public LRUCache(int capacity) {
this.capacity=capacity;
map=new HashMap<Integer,Node>();
dlist=new DLinkedList(0);
size=0;
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
Node node=map.get(key);
dlist.remove(node);
dlist.addFirst(node);
return node.value;
}
public void put(int key, int value) {
Node node=map.get(key);
if(node!=null){
map.remove(key);
dlist.remove(node);
size--;
}
if(capacity<=size){
if(capacity==0) return;
Node removeNode=dlist.tail.pre;
map.remove(removeNode.key);
dlist.remove(removeNode);
size--;
}
Node newNode=new Node(key,value);
map.put(key, newNode);
dlist.addFirst(newNode);
size++;
}
}
class DLinkedList{
Node head,tail;
int size;
public DLinkedList(int size) {
head=new Node(-1,0);
tail=new Node(-1,0);
size=this.size;
head.next=tail;tail.pre=head;
}
public void addFirst(Node node){
node.next=head.next;
head.next.pre=node;
node.pre=head;
head.next=node;
size++;
}
public Node remove(Node node){
if(node==null) return null;
Node before=node.pre;
Node after=node.next;
before.next=after;after.pre=before;
node.pre=null;node.next=null;
size--;
return node;
}
public void addFirst(int key,int val){
Node node=new Node(key,val);
addFirst(node);
}
}
class Node{
int key,value;
Node next,pre;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
/**
* 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 LinkedHashMap:
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache2 {
private LinkedHashMap<Integer, Integer> map;
private final int CAPACITY;
public LRUCache2(int capacity) {
CAPACITY = capacity;
map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true){
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CAPACITY;
}
};
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
else return map.get(key);
}
public void set(int key, int value) {
map.put(key, value);
}
}