LeetCode 146 [LRU Cache]
原題
為最近最少使用(LRU)快取策略設計一個資料結構,它應該支援以下操作:獲取資料(get)和寫入資料(set)。
1.獲取資料get(key)
:如果快取中存在key,則獲取其資料值(通常是正數),否則返回-1。
2.寫入資料set(key, value):如果key還沒有在快取中,則寫入其資料值。當快取達到上限,它應該在寫入新資料之前刪除最近最少使用的資料用來騰出空閒位置。
解題思路
第一過程中涉及membership的查詢 -> Hash Table
第二過程中涉及一個個的增、刪 -> Linked List (陣列不適合,陣列適合一批一批的增刪)
Linked List中的每個node要有next和prev屬性,要同時記錄Dummy(head)和tail
本解法採用的singly linked list所以hash表裡面存的key指向的是前一個node
越最近使用的存在連結串列的尾部,假設連結串列長度已經達到上限
如果新來的值存在於連結串列,則踢除,然後加到尾部
如果信賴的值不在連結串列中,則剔除開頭的值,然後新值加到尾部
完整程式碼
class LinkedNode:
def __init__(self, key=None, value=None, next=None):
self.key = key
self.value = value
self.next = next
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.hash = {}
self.head = LinkedNode()
self.tail = self.head
self.capacity = capacity
def push_back(self, node):
self.hash[node.key] = self.tail
self.tail.next = node
self.tail = node
def pop_front(self):
del self.hash[self.head.next.key]
self.head.next = self.head.next.next
self.hash[self.head.next.key] = self.head
# change "prev->node->next...->tail"
# to "prev->next->...->tail->node"
def kick(self, prev):
node = prev.next
if node == self.tail:
return
prev.next = node.next
if node.next is not None:
self.hash[node.next.key] = prev
node.next = None
self.push_back(node)
def get(self, key):
"""
:rtype: int
"""
if key not in self.hash:
return -1
self.kick(self.hash[key])
return self.hash[key].next.value
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: nothing
"""
if key in self.hash:
self.kick(self.hash[key])
self.hash[key].next.value = value
else:
self.push_back(LinkedNode(key, value))
if len(self.hash) > self.capacity:
self.pop_front()
相關文章
- Leetcode LRU CacheLeetCode
- [Leetcode]146.LRU快取機制LeetCode快取
- LeetCode-146- LRU 快取機制LeetCode快取
- LeetCode146 動手實現LRU演算法LeetCode演算法
- LeetCode第 146 號問題: LRU 快取機制LeetCode快取
- 146. LRU 快取快取
- 詳解leetcode146題【LRU (最近最少使用) 快取機制】(附js最優解法!)LeetCode快取JS
- LRU cache原理及go實現Go
- 動手實現一個 LRU cache
- LRU cache快取簡單實現快取
- 用 Go 實現一個 LRU cacheGo
- LRU Cache的原理和python的實現Python
- 【golang必備演算法】 Letecode 146. LRU 快取機制Golang演算法快取
- Android快取機制-LRU cache原理與用法Android快取
- Python 的快取機制: functools.lru_cachePython快取
- 通過原始碼學習@functools.lru_cache原始碼
- Python 中 lru_cache 的使用和實現Python
- 從 LRU Cache 帶你看面試的本質面試
- python自帶快取lru_cache用法及擴充套件(詳細)Python快取套件
- Leetcode LRU快取,陣列+結構體實現LeetCode快取陣列結構體
- 使用LinkedHashMap來實現一個使用LRU(Least Recently Used)演算法的cacheHashMapAST演算法
- 演算法題:設計和實現一個 LRU Cache 快取機制演算法快取
- lru
- 給vnTrader 1.92版本加入lru_cache快取讀取提速優化回測快取優化
- [ARC146C] Even XOR
- protobuf、LRU、sigleflight
- 146.synchronized同步方法與塊synchronized
- LRU 演算法演算法
- [Python手撕]LRUPython
- LRU快取機制快取
- library cache pin和library cache lock(一)
- library cache pin和library cache lock (zt)
- library cache pin和library cache lock(二)
- Guava CacheGuava
- Spring CacheSpring
- Service Worker Cache 和 HTTP Cache 的區別HTTP
- MySQL:Table_open_cache_hits/Table_open_cache_misses/Table_open_cache_overflowsMySql
- LRU 實現 通過 LinkedHashMapHashMap
- LRU演算法簡介演算法