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.
Difficulty: Hard
Solution: Use linked list to implement and hash map to track the Node by Key.
public class LRUCache {
Node head;
Node tail;
int count;
HashMap<Integer, Node> hm = new HashMap<Integer, Node>();
public LRUCache(int capacity) {
count = capacity;
head = null;
tail = null;
}
public void setHead(Node node){
node.next = head;
node.pre = null;
if(head!= null){
head.pre = node;
}
else{
tail = node;
}
head = node;
}
public void remove(Node node){
Node pre = node.pre;
Node next = node.next;
if(pre != null){
pre.next = next;
}
else{
head = next;
}
if(next != null){
next.pre = pre;
}
else{
tail = pre;
}
return;
}
public int get(int key) {
if(hm.containsKey(key)){
Node node = hm.get(key);
remove(node);
setHead(node);
return node.value;
}
return -1;
}
public void set(int key, int value) {
if(hm.containsKey(key)){
Node node = hm.get(key);
remove(node);
setHead(node);
node.value = value;
}
else{
if(hm.size() == count){
Node newNode = new Node(key, value);
setHead(newNode);
hm.put(newNode.key, newNode);
hm.remove(tail.key);
remove(tail);
}
else{
Node newNode = new Node(key, value);
setHead(newNode);
hm.put(newNode.key, newNode);
}
}
}
}
class Node{
int key;
int value;
Node pre;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}