Task12 LeetCode騰訊精選打卡

2021-10-17 08:58:55 字數 4655 閱讀 1224

運用你所掌握的資料結構,設計和實現乙個 lru (最近最少使用) 快取機制 。

實現 lrucache 類:

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

你的演算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?

輸入[「lrucache」, 「put」, 「put」, 「get」, 「put」, 「get」, 「put」, 「get」, 「get」, 「get」]

[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]

輸出[null, null, null, 1, null, -1, null, -1, 3, 4]

解釋lrucache lrucache = new lrucache(2);

lrucache.put(1, 1); // 快取是

lrucache.put(2, 2); // 快取是

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

lrucache.put(3, 3); // 該操作會使得關鍵字 2 作廢,快取是

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

lrucache.put(4, 4); // 該操作會使得關鍵字 1 作廢,快取是

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

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

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

class

dlinkednode

:def

__init__

(self, key=

0, value=0)

: self.key = key

self.value = value

self.prev =

none

self.

next

=none

class

lrucache

:def

__init__

(self, capacity:

int)

: self.capacity = capacity

self.size =

0 self.cache =

dict()

self.head = dlinkednode(

) self.tail = dlinkednode(

)#四個指標只需要初始化2個

self.head.

next

= self.tail

self.tail.prev = self.head

defget(self, key:

int)

->

int:

if key in self.cache:

node = self.cache[key]

self.movetohead(node)

return node.value

return-1

defput

(self, key:

int, value:

int)

->

none

:if key not

in self.cache:

#需要新建node

node = dlinkednode(key,value)

self.cache[key]

= node

#插入到最前端

self.addhead(node)

if self.size > self.capacity:

removed = self.removetail(

) self.cache.pop(removed.key)

else

:#移動尾結點到頭部 都需要操作 大小不變

node = self.cache[key]

self.movetohead(node)

node.value = value

#增加頭結點 連線四條線

defaddhead

(self,node)

: node.prev = self.head

node.

next

= self.head.

next

node.

next

.prev = node

self.head.

next

= node

self.size +=

1#刪除尾結點 返回被刪掉的結點

defremovetail

(self)

: node = self.tail.prev

self.removenode(node)

return node

#移除指定結點

給你鍊錶的頭結點 head ,請將其按 公升序 排列並返回 排序後的鍊錶 。

高階:你可以在 o(n log n) 時間複雜度和常數級空間複雜度下,對鍊錶進行排序嗎?

遍歷存入進list,然後經過排序後重新按序賦值。

class

solution

:def

sortlist

(self, head: listnode)

-> listnode:

#假設是對值排序 放到list裡面排序之後再放入

設計乙個支援 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。

push(x) —— 將元素 x 推入棧中。

pop() —— 刪除棧頂的元素。

top() —— 獲取棧頂元素。

getmin() —— 檢索棧中的最小元素。

class

minstack

:def

__init__

(self)

:"""

initialize your data structure here.

"""self.datalist =

self.minnum =

0#還有一種 就是每次push時拿到最小

Python學習 Task12 模組

import 模組名 from 模組名 import 函式名 import 模組名 as 新名字。import temperature print 32攝氏度 2f華氏度 temperature.c2f 32 小數點後列印兩位from temperature import c2f print 32攝...

Python程式設計基礎Task12

python自帶的open可以開啟指定文字編碼的檔案。只需要傳入encoding函式即可 2.length with open test.txt r as f for i in f print i word i.split del word len word 1 刪除換行符號 for i in ra...

Go學習之旅 Task12

在日常開發中,我們通常需要針對現有的功能進行單元測試,以驗證開發的正確性。在go標準庫中有乙個叫做testing的測試框架,可以進行單元測試,命令是go test 測試檔案通常是以xx test.go命名,放在同一包下面。現在假設現在需求是 完成兩個複數相加,我們只需要乙個函式便可以完成該任務。在開...