题目链接: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,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”