[leetcode] LRU Cache @ Python
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.
思路分析:可以考虑利用dict数据结构,查找时间是O(1)。但是Python的dictionary缺点是无序。而collections.OrderedDict是有序的, 后加入的元素一定排在先加入元素的后面, 操作和dictionary类似。所以本题目将利用此有序dictionary数据结构来实现。
作为背景知识,请复习:
import collections a = collections.OrderedDict() a[1] = 10 # 若1在a中就更新其值, 若1不在a中就加入(1, 10)这一对key-value。 a[2] = 20 a[3] = 30 del a[2] a.popitem(last = True) # 弹出尾部的元素 a.popitem(last = False) # 弹出头部的元素
代码如下:
class LRUCache: # @param capacity, an integer def __init__(self, capacity): LRUCache.capacity = capacity LRUCache.length = 0 LRUCache.dict = collections.OrderedDict() # @return an integer def get(self, key): try: value = LRUCache.dict[key] del LRUCache.dict[key] LRUCache.dict[key] = value return value except: return -1 # @param key, an integer # @param value, an integer # @return nothing def set(self, key, value): try: del LRUCache.dict[key] LRUCache.dict[key] = value except: if LRUCache.length == LRUCache.capacity: LRUCache.dict.popitem(last = False) LRUCache.length -= 1 LRUCache.dict[key] = value LRUCache.length +=1
参考致谢:
[1]http://chaoren.is-programmer.com/posts/43116.html
[2]http://www.cnblogs.com/zuoyuan/p/3701572.html (这个代码有75行,面试时效很差;但是是很好的对双向链表的练习)