Description
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.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
1 | LRUCache cache = new LRUCache( 2 /* capacity */ ); |
解法
用一个哈希表和一个双向链表实现,注意删除节点,移动节点时头尾节点的处理,同时如果put一个已有的key对,则更新并置于队尾即可。写的真心心累…
具体代码如下:
1 | class LRUCache { |