LeetCode 146 LRU快取機制

2021-10-06 11:51:42 字數 2114 閱讀 4943

運用你所掌握的資料結構,設計和實現乙個 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

雙向鍊錶:按照被使用的順序儲存鍵值對,靠近頭部的鍵值對是最近使用的,而靠近尾部的鍵值對是最近最少使用的。

雜湊表(hashmap):通過快取資料的鍵對映到其在雙向鍊錶中的位置。

對於 put 操作,首先判斷 key 是否存在:

class

lrucache

public

dlinkedlist

(int k,

int v)

}//雜湊表

private map

cache =

newhashmap

<

>()

;private

int size;

private

int capacity;

//設定頭尾結點,統一操作

private dlinkedlist head,tail;

public

lrucache

(int capacity)

public

intget

(int key)

//結點移到頭結點,表示最近使用過

movetohead

(listnode)

;return listnode.value;

}public

void

put(

int key,

int value)

}else

}/**

* 頭部增加結點

* @param node

*/private

void

addtohead

(dlinkedlist node)

/** * 刪除結點

* @param node

*/private

void

removenode

(dlinkedlist node)

/** * 結點移動到頭部

* @param node

*/private

void

movetohead

(dlinkedlist node)

/** * 刪除尾部結點

* @return

*/private dlinkedlist removetail()

}/**

* your lrucache object will be instantiated and called as such:

* lrucache obj = new lrucache(capacity);

* int param_1 = obj.get(key);

* obj.put(key,value);

*/

學渣帶你刷Leetcode146 LRU快取機制

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

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 如果金鑰不存在,則寫入其資料值。當快取容量...