LRU 雙向鍊錶 雜湊表 python

2021-10-17 09:37:52 字數 2870 閱讀 5225

通過雙向鍊錶和雜湊表的結合實現lru

class

node

:def

__init__

(self, key =

0, value=0)

: self.key = key

self.value = value

self.

next

=none

self.pre =

none

class

solution

:def

__init__

(self, max_size =0)

: self.dummy = node(

) self.tail = self.dummy

self.dic =

self.size =

0 self.max_size = max_size

defset(self, key, value)

:if key not

in self.dic:

node = node(key, value)

self.size +=

1# 只有不存在的點才要+size

else

: node = self.dic[key]

node.value = value

if node.

next

==none

:return

pre = node.pre

nxt = node.

next

pre.

next

= nxt

nxt.pre = pre # 一定要記得把下乙個node的pre調好

node.

next

=none

node.pre = self.tail

self.tail.

next

= node

self.tail = self.tail.

next

self.dic[key]

= node

if self.size > self.max_size:

node = self.dummy.

next

nxt = node.

next

self.dummy.

next

= nxt

if nxt !=

none

: nxt.pre = self.dummy # 一定要記得把下乙個node的pre調好

self.dic.pop(node.key)

# del self.dic[node.key]

self.size -=

1def

get(self, key)

:if key not

in self.dic:

return-1

node = self.dic[key]

if node.

next

==none

:# 當查到的元素是最後乙個的時候,不能使用下面的方法,因為node.pre = self.tail中node和tail是同乙個元素

return node.value

pre = node.pre

nxt = node.

next

pre.

next

= nxt

nxt.pre = pre # 一定要記得把下乙個node的pre調好 'nonetype' object has no attribute 'pre'

node.pre = self.tail

node.

next

=none

self.tail.

next

= node

self.tail = self.tail.

next

return node.value

deflru(self , operators , k)

:# write code here

self.max_size = k

rst =

i =0for arr in operators:

if arr[0]

==1: self.

set(arr[1]

, arr[2]

)elif arr[0]

==2: 1]

))# i+=1

# print(i, self.dic)

# cur = self.dummy.next

# tmp =

# while cur != none:

# print('/*-', end='')

# cur = cur.next

# print(tmp)

# cur = self.tail

# tmp2 =

# while cur != self.dummy:

# print('/*-', end='')

# cur = cur.pre

# print(tmp2)

return rst

146 LRU 快取機制(雙向鍊錶 雜湊表)

難度 中等 運用你所掌握的資料結構,設計和實現乙個 lru 最近最少使用 快取機制 實現 lrucache 類 lrucache int capacity 以正整數作為容量 capacity 初始化 lru 快取 int get int key 如果關鍵字 key 存在於快取中,則返回關鍵字的值,否...

LRU快取機制(雜湊鍊錶)

題目 參考 solution lru ce lue xiang jie he shi xian by labuladong 運用你所掌握的資料結構,設計和實現乙個 lru 最近最少使用 快取機制。它應該支援以下操作 獲取資料 get 和 寫入資料 put 獲取資料 get key 如果金鑰 key ...

鍊錶 LRU

鍊錶就是鏈式儲存資料的一種資料結構。雙向鍊錶每個資料儲存都包含他的前後資料節點的位置資訊 索引 指標 class dschain 搜尋資料,返回所在索引 int search t data return index public bool insert t data else head index ...