146. LRU Cache
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
Solution)
LRU Cache
class LRUCache {
class ListNode {
int key;
int val;
ListNode prev, next;
public ListNode(int key, int val) {
this.key = key;
this.val = val;
this.prev = this.next = null;
}
}
class DoublyLinkedList {
ListNode head, tail;
int size = 0;
public DoublyLinkedList() {
head = tail = null;
}
public void insert(ListNode node) {
if (head == null) {
head = tail = node;
size = 1;
} else {
tail.next = node;
node.prev = tail;
tail = node;
size++;
}
}
public void delete(ListNode node) {
if (head == null) return;
if (node.prev != null) {
node.prev.next = node.next;
} else {
head = node.next;
}
if (node.next != null) {
node.next.prev = node.prev;
} else {
tail = node.prev;
}
size--;
}
public int size() {
return this.size;
}
}
DoublyLinkedList list;
int capacity;
Map<Integer, ListNode> map;
public LRUCache(int capacity) {
this.capacity = capacity;
list = new DoublyLinkedList();
map = new HashMap<>();
}
public int get(int key) {
// if the value is hit, update the list
if (map.get(key) != null) {
list.delete(map.get(key));
ListNode node = new ListNode(key, map.get(key).val);
map.remove(key);
map.put(key, node);
list.insert(node);
return node.val;
}
return -1;
}
public void put(int key, int value) {
if (map.get(key) != null) {
list.delete(map.get(key));
map.remove(key);
} else if (list.size() == capacity) {
// remove head
map.remove(list.head.key);
list.delete(list.head);
}
ListNode node = new ListNode(key, value);
map.put(key, node);
list.insert(node);
}
}
/**
* 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);
*/