Skip to content

Commit bc45204

Browse files
eric496labuladong
authored andcommitted
Add Python 3 solution
1 parent c13bf2c commit bc45204

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

高频面试系列/LRU算法.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,73 @@ if (cap == cache.size()) {
219219

220220
![labuladong](../pictures/labuladong.png)
221221

222+
![eric wang](https://www.github.com/eric496) 提供 Python3 代码
223+
224+
```python
225+
class ListNode:
226+
def __init__(self, key: int, val: int):
227+
self.key = key
228+
self.val = val
229+
self.prev = None
230+
self.next = None
231+
232+
233+
class LRUCache:
234+
def __init__(self, capacity: int):
235+
# 最大容量
236+
self.cap = capacity
237+
self.cache = {}
238+
# 哨兵节点
239+
self.sentinel = ListNode(None, None)
240+
# 尾节点: 用于链表容量超过最大容量是快速定位、删除尾节点
241+
self.tail = ListNode(None, None)
242+
# 初始化双向链表
243+
self.sentinel.next = self.tail
244+
self.tail.prev = self.sentinel
245+
246+
def get(self, key: int) -> int:
247+
if key in self.cache:
248+
node = self.cache[key]
249+
# 从链表中删除该节点
250+
self.remove_node_from_list(node)
251+
# 把该节点添加到链表头部
252+
self.push_node_to_front(node)
253+
return node.val
254+
else:
255+
return -1
256+
257+
def put(self, key: int, value: int) -> None:
258+
# 如果该节点已经存在那么删除该节点
259+
if key in self.cache:
260+
self.remove_node_from_list(self.cache[key])
261+
262+
# 把该节点添加到链表头部
263+
node = ListNode(key, value)
264+
self.cache[key] = node
265+
self.push_node_to_front(node)
266+
267+
# 如果链表超过最大容量,删除链表尾部节点
268+
if len(self.cache) > self.cap:
269+
last_node = self.tail.prev
270+
self.remove_node_from_list(last_node)
271+
self.cache.pop(last_node.key)
272+
273+
# 从链表中删除节点
274+
def remove_node_from_list(self, node: "ListNode") -> None:
275+
prev = node.prev
276+
nxt = node.next
277+
prev.next = nxt
278+
nxt.prev = prev
279+
280+
# 添加节点到链表头部
281+
def push_node_to_front(self, node: "ListNode") -> None:
282+
nxt = self.sentinel.next
283+
self.sentinel.next = node
284+
node.next = nxt
285+
node.prev = self.sentinel
286+
nxt.prev = node
287+
```
288+
222289
[上一篇:二叉堆详解实现优先级队列](../数据结构系列/二叉堆详解实现优先级队列.md)
223290

224291
[下一篇:二叉搜索树操作集锦](../数据结构系列/二叉搜索树操作集锦.md)

0 commit comments

Comments
 (0)