LeetCode146 動手實現LRU演算法

2021-09-11 11:07:35 字數 1906 閱讀 2741

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

複製**

// doublylinkednode defines a node for double-linked-list

type doublylinkednode struct

// lrucache defines a object for cache

type lrucache struct

// constructor creates a cache object

func

constructor

(capacity int)

lrucache }

// get returns value by key

func

(l *lrucache)

get(key int)

int

//key not exist,return -1

return-1}

// put puts key-value pair into lrucache

func

(l *lrucache)

put(key int, value int)

else else

node := &doublylinkednode

l.nodes[key] = node

l.inserttofirst(node) }}

func

(l *lrucache)

removelast

() else

l.last = l.last.prev

}func

(l *lrucache)

movetofirst

(node *doublylinkednode)

// 策略是

// 如果是移動node

// 先刪除,再插入

l.inserttofirst(node)

}func

(l *lrucache)

inserttofirst

(node *doublylinkednode)

else

l.first = node

}複製**

LeetCode146 動手實現LRU演算法

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

leetcode 146 實現LRU演算法

lru 最近最少使用。不管是讀還是寫,都是對此資料重新整理他的時間 時間由雙向鍊錶的順序決定 class lrucache public node int key,int value private node dummyhead new node private node dummytail new...

LRU快取機制 leetcode146

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