Created
November 13, 2017 03:58
-
-
Save shailrshah/0ece3366e91332f3db62a84a0cf630aa to your computer and use it in GitHub Desktop.
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. 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 …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LRUCache { | |
int capacity; | |
Map<Integer, ListNode> map; | |
ListNode head, tail; | |
private static class ListNode { | |
int key, value; | |
ListNode prev, next; | |
ListNode(int key, int value) { | |
this.key = key; | |
this.value = value; | |
} | |
} | |
public LRUCache(int capacity) { | |
this.map = new HashMap<>(); | |
this.capacity = capacity; | |
} | |
public int get(int key) { | |
ListNode node = map.get(key); | |
if(node == null) return -1; | |
if(node != head){ | |
removeFromLinkedList(node); | |
insertToFrontOfLinkedList(node); | |
} | |
return node.value; | |
} | |
public void put(int key, int value) { | |
removeFromCache(key); | |
if(map.size() >= capacity && tail != null) | |
removeFromCache(tail.key); | |
ListNode node = new ListNode(key, value); | |
insertToFrontOfLinkedList(node); | |
map.put(key, node); | |
} | |
void removeFromCache(int key) { | |
removeFromLinkedList(map.get(key)); | |
map.remove(key); | |
} | |
void removeFromLinkedList(ListNode node) { | |
if(node == null) return; | |
if(node.prev != null) node.prev.next = node.next; | |
if(node.next != null) node.next.prev = node.prev; | |
if(node == tail) tail = node.prev; | |
if(node == head) head = node.next; | |
} | |
void insertToFrontOfLinkedList(ListNode node) { | |
if(head == null) { | |
head = node; | |
tail = node; | |
} else { | |
head.prev = node; | |
node.next = head; | |
head = node; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment