class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.cache = {}
self.queue = []
def updateQueue(self, key):
self.queue.remove(key)
self.queue.insert(0, key)
def get(self, key):
"""
:rtype: int
"""
if key in self.cache:
self.updateQueue(key)
return self.cache[key]
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
if key in self.cache:
self.queue.remove(key)
elif len(self.queue) == self.capacity:
del self.cache[self.queue.pop(-1)]
self.cache[key] = value
self.queue.insert(0, key)
# def __init__(self, capacity):
# self.dic = collections.OrderedDict()
# self.remain = capacity
#
# def get(self, key):
# if key not in self.dic:
# return -1
# v = self.dic.pop(key)
# self.dic[key] = v # set key as the newest one
# return v
#
# def put(self, key, value):
# if key in self.dic:
# self.dic.pop(key)
# else:
# if self.remain > 0:
# self.remain -= 1
# else: # self.dic is full
# self.dic.popitem(last=False)
# self.dic[key] = value
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
python_leetcode面试题解之第146题LRU缓存_题解.zip (1个子文件)
python_leetcode面试题解之第146题LRU缓存_题解
146_LRU_Cache.py 1KB
共 1 条
- 1
资源评论
Ddddddd_158
- 粉丝: 1173
- 资源: 295
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功