LeetCode LRU Cache (implemented in Java)
LRU Cache
Question requirements
Design and implement a data structure for Least Recently Used (LRU) cache. It shocould support the following operations:get
Andset
.
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 shocould invalidate the least recently used item before inserting a new item.
Refer to the two blogs
Http://blog.csdn.net/beiyeqingteng/article/details/7010411
Http://gogole.iteye.com/blog/692103
It is worth mentioning that LruCache is very effective for caching images on the Android platform. for the official implementation of LruCache, refer
Http://blog.csdn.net/linghu_java/article/details/8574102
In fact, LruCache does not do anything special. It only provides LinkedHashMap with a layer. What truly implements the lru algorithm is LinkedHashMap.
During the interview, the interviewer may not like you to use javashashmap.
import java.util.Hashtable;public class LRUCache { int capacity; int size; CacheNode first; CacheNode last; Hashtable
nodes = new Hashtable
(); class CacheNode{ CacheNode prev; CacheNode next; int key; int value; } public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { CacheNode node = nodes.get(key); if (node == null) return -1; moveToHead(node); return node.value; } public void set(int key, int value) { CacheNode node = nodes.get(key); if (node == null){ if (size >= capacity){ if (last != null){ nodes.remove(last.key); } removeLast(); }else{ ++size; } node = new CacheNode(); } node.key = key; node.value = value; moveToHead(node); nodes.put(key, node); } private void removeLast(){ if (last != null){ if (last.prev != null){ last.prev.next = null; }else{ first = null; } last = last.prev; } } private void moveToHead(CacheNode node){ if (node == first) return; if (node.prev != null) node.prev.next = node.next; if (node.next != null) node.next.prev = node.prev; if (last == node) last = node.prev; if (first != null){ first.prev = node; } node.next = first; first = node; node.prev = null; if (last == null) last = first; }}