LRU Cache
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.
Solution: Data structure: Hashmap. When we operate the element, it will change the position in the linkedlist.
public class Solution {
int capacity;
HashMap<Integer, Node> map;
Node head = null;
Node end = null;
// @param capacity, an integer
public Solution(int capacity) {
// write your code here
this.capacity = capacity;
map = new HashMap<Integer, Node>();
}
// @return an integer
public int get(int key) {
// write your code here
if(map.containsKey(key)) {
Node n = map.get(key);
remove(n);
setHead(n);
return map.get(key).val;
}
return -1;
}
// @param key, an integer
// @param value, an integer
// @return nothing
public void set(int key, int value) {
// write your code here
if(map.containsKey(key)) {
Node node = map.get(key);
node.val = value;
map.put(key, node);
remove(node);
setHead(node);
}
else {
if(map.size() < capacity) {
Node n = new Node(key, value);
map.put(key, n);
setHead(n);
}
else {
//must remove hashmap first. Because remove(end) will change the end pointer.
map.remove(end.key);
remove(end);
Node n = new Node(key, value);
map.put(key, n);
setHead(n);
}
}
}
public void setHead(Node n) {
if(head == null) {
//Initialization
head = n;
end = n;
}
else {
n.next = head;
head.prev = n;
head = n;
}
}
public void remove(Node n) {
if(head.equals(n)) {
head = n.next;
n.next = null;
}
else if(end.equals(n)) {
end = n.prev;
n.prev = null;
}
else {
n.next.prev = n.prev;
n.prev.next = n.next;
n.next = null;
n.prev = null;
}
}
}
class Node {
int key;
int val;
Node prev;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}