题目来源:
https://leetcode.com/problems/lru-cache/
实现一个LRU缓存。直接上代码。
代码(python):
1 class LRUCache(object): 2 3 def __init__(self, capacity): 4 """ 5 :type capacity: int 6 """ 7 LRUCache.capacity = capacity 8 LRUCache.length = 0 9 LRUCache.dict = collections.OrderedDict()10 11 def get(self, key):12 """13 :rtype: int14 """15 try:16 value = LRUCache.dict[key]17 del LRUCache.dict[key]18 LRUCache.dict[key] = value19 return value20 except:21 return -122 23 def set(self, key, value):24 """25 :type key: int26 :type value: int27 :rtype: nothing28 """29 try:30 del LRUCache.dict[key]31 LRUCache.dict[key] = value32 except:33 if LRUCache.length == LRUCache.capacity:34 LRUCache.dict.popitem(last = False)35 LRUCache.length -= 136 LRUCache.dict[key] = value37 LRUCache.length += 138