class Node:
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.capacity = capacity
self.length = 0
self.map = {}
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if key in self.map:
self.remove(self.map[key])
self.refresh(self.map[key])
return self.map[key].value
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.map:
self.map[key].value = value
self.remove(self.map[key])
self.refresh(self.map[key])
else:
if self.length == self.capacity:
t = self.head.next.key
self.remove(self.head.next)
del self.map[t]
node = Node(key, value)
self.refresh(node)
self.map[key] = node
else:
node = Node(key, value)
self.refresh(node)
self.map[key] = node
self.length += 1
def remove(self, node):
node.next.prev = node.prev
node.prev.next = node.next
def refresh(self, node):
node.prev = self.tail.prev
self.tail.prev.next = node
node.next = self.tail
self.tail.prev = node
def show(self):
cur = self.head.next
while cur.next:
print(cur.key,cur.value, end="|")
cur = cur.next
print()
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
[Python手撕]LRU
相關文章
- [Python手撕]LFUPython
- [Python手撕]接雨水Python
- [Python手撕]完全平方數Python
- [Python手撕]爬樓梯Python
- [Python手撕]公交路線Python
- [Python手撕]最大子陣列和Python陣列
- 《我們一起進大廠》系列-Redis哨兵、持久化、主從、手撕LRURedis持久化
- 手撕OkHttpHTTP
- [SQL手撕]SQL
- [Python手撕]判斷二分圖Python
- [Python手撕]滑動視窗最大值Python
- [Python手撕]搜尋二維矩陣Python矩陣
- 前端筆試題——手撕快速排序(保姆級手撕)前端筆試排序
- [Python手撕]使用最小花費爬樓梯Python
- [Python手撕]判斷平衡二叉樹Python二叉樹
- 手撕Flutter開發Flutter
- [Python手撕]判斷二叉搜尋樹Python
- [Python手撕]不同的二叉搜尋樹Python
- [Python手撕]執行操作使頻率分數最大Python
- [Python手撕]兩個升序陣列的中位數Python陣列
- 手撕面試題ThreadLocal!!!面試題thread
- 手撕字串操作函式字串函式
- 手撕AVL樹(C++)C++
- css手撕奧運五環CSS
- [Java面試]經典手撕Java面試
- [Python手撕]二叉樹中的最大路徑和Python二叉樹
- 手寫一個LRU工具類
- 手撕Vuex-提取模組資訊Vue
- [Java手撕]迴圈列印ABCJava
- [Python手撕]零錢兌換(組合總數,需要去重)Python
- [Python手撕]有序陣列中的單一元素Python陣列
- 動手實現一個 LRU cache
- 前端面試-手撕程式碼篇前端面試
- 通過例子手撕架構模式架構模式
- 面試常見手撕程式碼題面試
- 手撕記憶體操作函式記憶體函式
- 手撕Vuex-安裝模組方法Vue
- 手撕Vuex-實現mutations方法Vue