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持久化
- [Python手撕]判斷二分圖Python
- [Python手撕]搜尋二維矩陣Python矩陣
- 手撕OkHttpHTTP
- [SQL手撕]SQL
- 手撕HashMapHashMap
- [Python手撕]使用最小花費爬樓梯Python
- [Python手撕]滑動視窗最大值Python
- [Python手撕]判斷平衡二叉樹Python二叉樹
- 前端筆試題——手撕快速排序(保姆級手撕)前端筆試排序
- [Python手撕]不同的二叉搜尋樹Python
- [Python手撕]判斷二叉搜尋樹Python
- 手撕彙編。。。
- [Python手撕]兩個升序陣列的中位數Python陣列
- [Python手撕]執行操作使頻率分數最大Python
- 手撕Flutter開發Flutter
- 手寫一個LRU工具類
- [Python手撕]二叉樹中的最大路徑和Python二叉樹
- 手撕面試題ThreadLocal!!!面試題thread
- 手撕正規表示式
- 手撕AVL樹(C++)C++
- 手撕字串操作函式字串函式
- 動手實現一個 LRU cache
- [Python手撕]零錢兌換(組合總數,需要去重)Python
- [Python手撕]有序陣列中的單一元素Python陣列
- css手撕奧運五環CSS
- [Java手撕]迴圈列印ABCJava
- [Java面試]經典手撕Java面試
- 成都開手撕發具票
- 天津開手撕發具票
- Go 語言手寫本地 LRU 快取Go快取
- LRU Cache的原理和python的實現Python