- 1
- 2
- 3
- 4
- 5
LRUCache哈希表与双向链表实现
资料介绍
LRU(Least Recently Used)缓存机制是一种常用的缓存淘汰策略,其核心思想是当缓存空间满时,优先淘汰最近最少使用的元素。以下是基于哈希表和双向链表实现的LRUCache代码,具有O(1)时间复杂度的get和put操作:
class DLinkedNode:
def __init__(self, key=0, value=0):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cache = dict()
# 使用伪头部和伪尾部节点,避免空指针判断
self.head = DLinkedNode()
self.tail = DLinkedNode()
self.head.next = self.tail
self.tail.prev = self.head
self.capacity = capacity
self.size = 0
def get(self, key: int) -> int:
if key not in self.cache:
return -1
# 如果key存在,通过哈希表定位,移到头部
node = self.cache[key]
self.moveToHead(node)
return node.value
def put(self, key: int, value: int) -> None:
if key not in self.cache:
# 如果key不存在,创建新节点
部分文件列表
| 文件名 | 大小 |
| 1776745402LRUCache哈希表与双向链表实现.docx | 13K |
最新上传
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏15.00元 3天前
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏10.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic下载 打赏310.00元 3天前
用户:gsy幸运
-
21ic下载 打赏310.00元 3天前
用户:小猫做电路
-
21ic下载 打赏360.00元 3天前
用户:mulanhk
-
21ic下载 打赏230.00元 3天前
用户:江岚
-
21ic下载 打赏230.00元 3天前
用户:潇潇江南
-
21ic下载 打赏210.00元 3天前
用户:zhengdai
-
21ic下载 打赏160.00元 3天前
用户:lanmukk
-
21ic下载 打赏130.00元 3天前
用户:jh03551
-
21ic下载 打赏110.00元 3天前
用户:liqiang9090
-
21ic下载 打赏110.00元 3天前
用户:jh0355
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic小能手 打赏5.00元 3天前
-
21ic下载 打赏20.00元 3天前
用户:w178191520
-
21ic下载 打赏30.00元 3天前
用户:sun2152
-
21ic下载 打赏30.00元 3天前
用户:xuzhen1
-
21ic下载 打赏20.00元 3天前
用户:w993263495
-
21ic下载 打赏15.00元 3天前
用户:kk1957135547
-
21ic下载 打赏15.00元 3天前
用户:eaglexiong
-
21ic下载 打赏15.00元 3天前
用户:w1966891335
-
21ic下载 打赏25.00元 3天前
用户:烟雨




全部评论(0)