力扣刷题(python)50天——第三十四天:LRU缓存机制
题目描述
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法
由于我们需要同时记录key的value以及调用记录,因此采用双字典来记录。字典比列表好在用key调用更加方便且速度更快。
解答
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.maxlength=capacity
self.dict_val={}
self.dict_rec={}
self.length=0
self.flag=-10
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.dict_val:
self.dict_rec[key]=self.flag
self.flag-=1
return self.dict_val[key]
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key not in self.dict_val:
self.length+=1
self.dict_val[key]=value
self.dict_rec[key]=self.flag
self.flag-=1
if self.length>self.maxlength:
use_least=float('-inf')
for each in self.dict_rec:
if use_least<=self.dict_rec[each]:
use_least=self.dict_rec[each]
flag=each
del self.dict_rec[flag]
del self.dict_val[flag]
self.length-=1
else:
self.dict_val[key]=value
self.dict_rec[key]=self.flag
self.flag-=1
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
其实在这种方法之前,我使用
self.dict_rec[key]=0
for each in self.dict_rec:
self.dict_rec[each]+=1
来更新记录的哈希表,但现在觉得好傻。。。。一直超时,根据之前很多题的经验,我知道是in出了问题,逐个检查in能否改进,解决了问题,优化了算法。
执行结果
两种复杂度均较高!!!!!!!!
提升:
有序字典
https://leetcode-cn.com/problems/lru-cache/solution/lru-huan-cun-ji-zhi-by-leetcode/
哈希+双向链表
https://leetcode-cn.com/problems/lru-cache/solution/shu-ju-jie-gou-fen-xi-python-ha-xi-shuang-xiang-li/