劍指offer刷題記錄 順序刷題第四周

2021-10-17 08:52:44 字數 3206 閱讀 1950

class

solution

:def

levelorder

(self, root: treenode)

-> list[list[

int]]:

ifnot root:

return

res =

queue = collections.deque(

) i=

0while queue:

tmp =

for _ in

range

(len

(queue)):

node = queue.popleft(

)if i%2==

0: i+=

1else: :

:-1]

) i+=

1return res

class

solution

:def

levelorder

(self, root: treenode)

-> list[list[

int]]:

# 特殊情況,root為空

ifnot root:

return

res =

queue = collections.deque(

)while queue:

tmp =

for _ in

range

(len

(queue)):

node = queue.popleft(

)return res

class

solution

:def

levelorder

(self, root: treenode)

-> list[

int]:if

not root:

return

res =

# 要建立乙個結點序列,儲存左右結點,這樣才可以每層從左到右。如果是直接遞迴,是深度優先輸出。

queue = collections.deque(

)while queue:

node = queue.popleft(

)return res

class

solution

:def

validatestacksequences

(self, pushed: list[

int]

, popped: list[

int])-

>

bool

: res =

i =0for ele in pushed:

while res and res[-1

]== popped[i]

: res.pop(

) i+=

1return

not res

class

minstack

:def

__init__

(self)

:"""

initialize your data structure here.

"""self.a , self.b =

,[]def

push

(self, x:

int)

->

none:if

not self.b or self.b[-1

]>=x:

defpop

(self)

->

none

:if self.a.pop(

)== self.b[-1

]:self.b.pop(

)def

top(self)

->

int:

return self.a[-1

]if self.a else

none

defmin

(self)

->

int:

# 直接用了min函式,不好!應該自己寫乙個輔助棧,儲存最小值。所以有兩個list,第二個用於儲存min。

return self.b[-1

]

class

solution

:def

spiralorder

(self, matrix: list[list[

int]])

-> list[

int]

:# python可以將第一行加入res,剩下的旋轉,再選取第一行加入res,如此。

res =

while matrix:

res += matrix.pop(0)

matrix =

list

(zip

(*matrix))[

::-1

]# list(zip(*matric))是矩陣每列為乙個元素

return res

class

solution

:def

mergetwolists

(self, l1: listnode, l2: listnode)

-> listnode:

# 用0新建乙個鍊錶,用cur移動構建鍊錶,返回res.next得到完整鍊錶

# 思路:不斷將小的結點進行拼接,直至乙個為null,將另乙個拼接在後面

res = cur = listnode(0)

while l1 and l2:

if l1.val >= l2.val:

cur.

next

= l2

l2 = l2.

next

else

: cur.

next

= l1

l1 = l1.

next

cur = cur.

next

cur.

next

= l1 if l1 else l2

return res.

next

劍指 offer 刷題記錄

任誰都躲不過找工作的問題,好希望能多準備一些時間,奈何時間不等人,每天刷幾道題,並且記錄下來吧 def replacespace s write code here num space 0 new s for i in range len s if i num space 1 for i in ra...

劍指offer刷題記錄

遞迴法 鍊錶的後續遍歷,並用self.k來記錄倒數節點的位置,找到了就返回找到的節點,否則返回none coding utf 8 class listnode def init self,x self.val x self.next none class solution def init self...

劍指offer刷題記錄 綜合

將乙個字串轉換成乙個整數,要求不能使用字串轉換整數的庫函式。數值為0或者字串不是乙個合法的數值則返回0 輸入描述 輸入乙個字串,包括數字字母符號,可以為空 輸出描述 如果是合法的數值表達則返回該數字,否則返回0 做這個題目做的真的很煩,最麻煩的就是判斷當前是否越界。可儲存的最大的正數末位為7,可儲存...