146. LRU Cache
Analysis:
Although the problem only asks for implementing two operaions. It actually requires more than that. The two obvious and a few hidden required operations are:
- get: access value by key in O(1) and update its “freshness”
- put: add (key, value) pair in data structure and set it to be the freshest
- delete: delete the least recently used pair
- update: update pair’s value and “freshness” = delete and move to end
First, if we want “get” to be done in O(1), hashing is a must. And we need to keep track of the “least recently used” element, hence a queue (FIFO) is considered. But if queue is used, updating the freshness of the pair will cost linear time, which is why a linklist should be used. So we can use hashing to map key to a node, where the value is saved. To update a node’s freshness from the linklist, we need to delete it from its original position, for which we need to not only know its next but also its pre — so we need to used double linklist! Finally, to delete the LRU from the hash table, we also need the key stored in the coresponding node. So now we have somthing like:
hash | key 1 | key 2 | key 3 | … |
---|---|---|---|---|
double linklist | (k1, v1) | (k2, v2) | (k3, v3) | … |
Trick: Python has a class collections.OrderedDict()
, which is a dict that keeps track of the insertion order…
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 its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
1 | LRUCache cache = new LRUCache( 2 /* capacity */ ); |
Soulution:
1 | class ListNode: |
1 | # collections.OrderedDict() |