题目链接:https://leetcode.com/problems/lru-cache/
代码
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity=capacity
self.dic=collections.OrderedDict()
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.dic:
return -1
v=self.dic.pop(key)
self.dic[key]=v
return v
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.dic:
self.dic.pop(key)
else:
if self.capacity > 0:
self.capacity-=1
else:
self.dic.popitem(last=False)
self.dic[key]=value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
思路详解
LRU:(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”

本文详细解析了LRU(最近最少使用)缓存算法的原理及其实现方式,通过Python代码展示了如何利用OrderedDict来高效地维护一个具有固定大小的缓存,当缓存满时,能够自动移除最近最少使用的元素。

332

被折叠的 条评论
为什么被折叠?



