题目
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
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.
解答
LRU Cache,是一种经典的Cache结构。考虑这几点:
- 第一点:确定存储Cache元素的数据结构。Cache一般是顺序结构,在Cache的所有元素中,最近访问的应该放在前面,最久没访问的应该放在靠后的位置。如果用数组来组织,主要问题是移动cache中的某个元素位置(如插到头部或从尾部删除)时,不可避免地要改变部分或全部元素的位置,代价太大。如果用单链表来组织,移动元素位置只需要改变链表节点的next指针。但在把最近访问的元素插到头部,或者从尾部删除最久没有访问的元素时,需要从前往后遍历链表,来确定被操作节点的前驱节点的位置,详细解释可参考LRU cache implementation - Is a double linked list necessary ? 。因此,最终确定用来存放cache数据的结构是双向链表,它很好地解决了上面提到的两个问题。
- 第二点:设计查找Cache元素的数据结构。众所周知,访问链表只能从前往后依次遍历。这种方式可行,但不高效。而题目中给出了元素的key和value,所以很容易联想到使用哈希表。其中,哈希表的键是元素的key,值是元素在链表中节点的地址指针。
综