LRU Cache
Hard
Question
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
getandset.
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.
Analysis
HashMap + Doubly LinkedList
LRU,也就是least recently used,最近使用最少的;这样一个数据结构,能够保持一定的顺序,使得最近使用过的时间或者顺序被记录,实际上,具体每一个item最近一次何时被使用的,并不重要,重要的是在这样的一个结构中,item的相对位置代表了最近使用的顺序;满足这样考虑的结构可以是链表list或者数组array,不过前者更有利于insert和delete的操纵,此外,需要记录这个链表的head和tail,方便进行移动到tail或者删除head的操作,即:head.next作为最近最少使用的item,tail.prev为最近使用过的item,在set时,如果超出capacity,则删除head.next,同时将要插入的item放入tail.prev, 而get时,如果存在,只需把item更新到tail.prev即可。
这样set与get均为O(1)时间的操作 (HashMap Get/Set + LinkedList Insert/Delete),空间复杂度为O(n), n为capacity。
LInkedHashMap
使用LinkedHashMap能很方便地实现LRU,定义好access-order,自定义removeEldestEntry()。
Solution
*(Preferred Implementation) Use Doubly Linked List
Another doubly linked list
Using LinkedHashMap
Note for LinkedHashMap:
Follow-up for LRU Cache
Concurrent LRU cache implementation
See stackoverflow:
https://stackoverflow.com/questions/40239485/concurrent-lru-cache-implementation
If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the
Collections.synchronizedMapmethod. This is best done at creation time, to prevent accidental unsynchronized access to the map:
The best you can do is to make it thread-safe is to wrap it with Collections.synchronizedMap(map) as explained in the JavaDoc:
However it is not enough to make it fully thread-safe you sill need to protect any iteration over the content of the map using the instance of the wrapped map as object's monitor:
Reference
https://www.programcreek.com/2013/03/leetcode-lru-cache-java/
Last updated
Was this helpful?