题解 | #设计LRU缓存结构#
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
# Your Solution object will be instantiated and called as such: # solution = Solution(capacity) # output = solution.get(key) # solution.set(key,value) from collections import OrderedDict class Solution: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key: int) -> int: if key not in self.cache: return -1 else: # if the item exist, mark it as the most recently used self.cache.move_to_end(key) return self.cache[key] def set(self, key: int, value: int) -> None: self.cache[key] = value self.cache.move_to_end(key) # if the cache size exceed the capacity, remove the least used item if len(self.cache) > self.capacity: self.cache.popitem(last=False)