- [x] ### HashMap
- [x] ### Double Linked List
146.LRU Cache(HashMap + Double Linked List)
Design and implement a data structure forLeast Recently Used (LRU) cache. It should support the following operations:getandput.
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 inO(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
class LRUCache {
private Node head;
private Node tail;
HashMap<Integer, Node> map;
int capacity;
public LRUCache(int capacity) {
head = null;
tail = null;
this.capacity = capacity;
map = new HashMap<Integer, Node>();
}
public int get(int key) {
Node node = map.get(key);
if (node == null) {
return -1;
}else{
//don't forget to update the head pointer
if (node != head) {
if (node == tail) {
tail = tail.next;
}else{
node.prev.next = node.next;
node.next.prev = node.prev;
}
head.next = node;
node.prev = head;
node.next = null;
head = node;
}
}
return node.val;
}
// t t head
// (1,1) <-> null<-(2,2) <-> (3,3) <-> (1,3) -> null
// update (1,3)
//
public void put(int key, int value) {
//two cases : if there exists the node for the key or not;
Node node = map.get(key);
if (node != null) {//if exists, update value,
node.val = value;
if (node != head) {
if (node == tail) {
tail = tail.next; // delete the node for now and insert it into the head positon
}else{
// delete the node for now and insert it into the head positon
node.prev.next = node.next;
node.next.prev = node.prev;
}
//insert the node
head.next = node;
node.prev = head;
node.next = null;
head = node;
}
}else{
node = new Node(key,value);
if (capacity == 0) {
Node temp = tail;
tail = tail.next;
map.remove(temp.key);
capacity++;
} //first remove and then add
if (head == null && tail == null) {
tail = node;
}else{
head.next = node;
node.prev = head;
node.next = null;
}
head = node;
map.put(key, node);
capacity--;
}
}
private class Node{
int key;
int val;
Node prev;
Node next;
private Node(int key, int val) {
this(key,val,null,null);
}
private Node(int key, int val, Node prev, Node next) {
this.key = key;
this.val = val;
this.prev = prev;
this.next = next;
}
}
}
/**
* 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);
*/