中等
技术面试0 次浏览

设计一个简单的缓存系统,要求实现基本的缓存读写操作,并且当缓存满时,采用 LRU(最近最少使用)策略淘汰数据。

算法工程师
缓存系统LRU 策略数据结构设计

答题要点

可以使用 Python 中的 OrderedDict 来实现 LRU 缓存系统。OrderedDict 是一种有序的字典,它可以记住元素插入的顺序。当进行元素访问时,将访问的元素移动到字典的末尾,这样字典的头部元素就是最近最少使用的元素。以下是实现代码: python from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = OrderedDict() def get(self, key): if key in self.cache: self.cache.move_to_end(key) return self.cache[key] return -1 def put(self, key, value): if key in self.cache: self.cache.move_to_end(key) self.cache[key]=value if len(self.cache) > self.capacity: self.cache.popitem(last = False) 在上述代码中,`__init__` 方法用于初始化缓存系统,设置缓存容量和创建 OrderedDict 实例。`get` 方法用于获取缓存中的元素,如果元素存在,将其移动到字典末尾并返回值;如果不存在,返回 -1。`put` 方法用于插入或更新缓存元素,如果元素已存在,将其移动到字典末尾;如果缓存已满,删除字典头部的元素。该缓存系统的读写操作时间复杂度均为 O(1)。