8月份 Leetcode hot 100 刷麻了(可以说就是背思路 最优解了) 最近两天还看codetop 高频算法题 看到题就想到最优的思路 最后 自己总结文档 每天花半个小时就是打开看 [奋斗][奋斗][奋斗][奋斗][奋斗][奋斗][奋斗]lslj4qcpwg.feishu.cn 最近发现LRU缓存考的次数最多

> 还是py优雅
```python
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
# from collections import OrderedDict
# OrderedDict = dict + 双向链表
self.cache = OrderedDict() # key -> value

def get(self, key: int) -> int:
if key not in self.cache: # 没有这本书
return -1
# 有这本书,把这本书抽出来,放到最上面(last=False 表示移到链表头)
self.cache.move_to_end(key, last=False)
return self.cache[key]

def put(self, key: int, value: int) -> None:
self.cache[key] = value # 添加 key value 或者更新 value
# 把这本书抽出来,放到最上面(last=False 表示移到链表头)
self.cache.move_to_end(key, last=False)
if len(self.cache) > self.capacity: # 书太多了
self.cache.popitem() # 去掉最后一本书
```
展开
半夜想吃披萨于2025-09-07 07:32发布的图片
半夜想吃披萨于2025-09-07 07:32发布的图片
评论