LRU Cache
Source
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.
Java
public class Solution {
HashMap<Integer, Node> map = new HashMap<Integer, Node>();
Node head=null;
Node tail=null;
int capacity=0;
public Solution(int capacity) {
this.capacity=capacity;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
Node node = map.get(key);
Node preNode = node.pre;
Node nextNode = node.next;
if(nextNode!=null){
if(preNode==null){
head=nextNode;
nextNode.pre=null;
}
else{
preNode.next=nextNode;
nextNode.pre = preNode;
}
tail.next=node;
node.pre=tail;
node.next=null;
tail=node;
}
return node.value;
}
public void set(int key, int value) {
if(map.containsKey(key)){
get(key);
map.get(key).value=value;
}
else{
Node node = new Node(key, value);
if(map.size()==this.capacity){
if(head!=null){
Node oldHead = head;
head=head.next;
if(head!=null){
head.pre=null;
}
map.remove(oldHead.key);
}
}
if(head==null){
head=node;
tail=node;
}else{
tail.next=node;
node.pre=tail;
tail=node;
}
map.put(key, node);
}
}
class Node{
int key;
int value;
Node pre=null;
Node next=null;
public Node(int key, int value){
this.key=key;
this.value=value;
}
}
}