leetcode146 LRU快取機制

2021-09-13 16:03:28 字數 1673 閱讀 5102

運用你所掌握的資料結構,設計和實現乙個 lru (最近最少使用) 快取機制。它應該支援以下操作: 獲取資料 get 和 寫入資料 put 。

獲取資料 get(key) - 如果金鑰 (key) 存在於快取中,則獲取金鑰的值(總是正數),否則返回 -1。

寫入資料 put(key, value) - 如果金鑰不存在,則寫入其資料值。當快取容量達到上限時,它應該在寫入新資料之前刪除最近最少使用的資料值,從而為新的資料值留出空間。

高階:你是否可以在 o(1) 時間複雜度內完成這兩種操作?

示例:lrucache cache = new lrucache( 2 / 快取容量 / );

cache.put(1, 1);

cache.put(2, 2);

cache.get(1); // 返回 1

cache.put(3, 3); // 該操作會使得金鑰 2 作廢

cache.get(2); // 返回 -1 (未找到)

cache.put(4, 4); // 該操作會使得金鑰 1 作廢

cache.get(1); // 返回 -1 (未找到)

cache.get(3); // 返回 3

cache.get(4); // 返回 4

乙個dict記錄key value,乙個list記錄訪問情況:

class

lrucache

:def

__init__

(self, capacity:

int)

: self.cap = capacity

self.

dict

=# 記錄key,value

self.

list=[

]# 記錄訪問順序,從舊到新

defget

(self, key:

int)

->

int:

if key not

in self.

dict

:return-1

self.

list

.remove(key)

self.

list

return self.

dict

[key]

defput

(self, key:

int, value:

int)

->

none

:if key in self.

dict

: self.

dict

[key]

= value

self.

list

.remove(key)

self.

list

else:if

len(self.

list

)== self.cap:

del self.

dict

[self.

list[0

]]self.

list

= self.

list[1

:]self.

dict

[key]

= value

self.

list

雙向鍊錶+雜湊的做法以後補充~

學渣帶你刷Leetcode146 LRU快取機制

運用你所掌握的資料結構,設計和實現乙個 lru 最近最少使用 快取機制。它應該支援以下操作 獲取資料 get 和 寫入資料 put 獲取資料 get key 如果金鑰 key 存在於快取中,則獲取金鑰的值 總是正數 否則返回 1。寫入資料 put key,value 如果金鑰已經存在,則變更其資料值...

LeetCode 146 LRU快取機制

運用你所掌握的資料結構,設計和實現乙個 lru 最近最少使用 快取機制。它應該支援以下操作 獲取資料get和 寫入資料put。獲取資料get key 如果金鑰 key 存在於快取中,則獲取金鑰的值 總是正數 否則返回 1。寫入資料put key,value 如果金鑰不存在,則寫入其資料值。當快取容量...

LeetCode 146 LRU快取機制

使用hash map和雙向鍊錶來做這題 class lrucache int cachesize int currentsize unordered mapnodes cachenode head cachenode last lrucache int capacity 獲取某個節點如果存在返回並且...