劍指offer刷題日記 棧 佇列 堆 雜湊表

2021-10-05 17:53:31 字數 3224 閱讀 8485

棧05-兩個棧實現佇列(python)

#stack1入 stack2出

class

solution

: def __init__

(self)

: self.stack1=

self.stack2=

def push

(self,node)

: self.stack1.

(node)

def pop

(self):if

len(self.stack1)

==0 or len

(self.stack2)==0

:return

elif len

(self.stack2)==0

:while

len(self.stack1)

>0:

self.stack2.

(self.stack1.

pop(

))

棧20-包含min函式的棧(python)

#輔助棧minstack

class

solution

: def __init__

(self)

: self.stack=

self.minstack=

def push

(self,node)

:if not self.stack:

self.stack.

(node)

else

:if self.minstack[-1

]self.minstack.

(self.minstack[-1

])else

: self.minstack.

(node)

def pop

(self)

: self.stack.

pop(-1

) self.minstack.

pop(-1

) def top

(self)

: self.stack.

pop(-1

) def min

(self)

: self.minstack.

pop(-1

)

棧21-判斷棧的壓入彈出(python)

#stack1入 stack2出

class

solution

: def ispoporder

(self,pushv,popv)

: stack=

for i in pushv:

stack.

(i)while stack and stack[-1

]==popv[0]

: stack.

pop(

) popv.

pop(0)

iflen

(stack)==0

:return true

else

:return false

棧044-反轉單詞順序列(python)

#按空格拆分

class

solution

: def reversesetence

(self,s)

: stack=

[n for n in s.

split

(' ')]

stack.

reverse()

return''.

join

(stack)

佇列064-滑動視窗的最大值(python)

class

solution

: def maxwindows

(self,num,size)

:if not nums or size<=0:

return

queue=

res=

for i in

range

(len

(num)):

while queue and queue[0]

<=i-size:

queue.

pop(0)

while queue and nums[i]

>num[queue[-1

]]: queue.

pop(-1

) queue.

(i)if i>=size-1:

res.

(num[queue[0]

)return res

堆29-最小的k個數(python)

class

solution

: def getleastnumbers_solution

(self,tinput,k)

:if not tinput or k>

len(tinput)

:return

tinput=self.

quicksort

(tinput)

return tinput[

:k] def quicksort

(self,list)

:if not list:

return

pivot=list[0]

left=self.

quicksort

([x for x in list[1:

]if xright=self.

quicksort

([x for x in list[1:

]if x>=pivot)

return left+

[pivot]

+right

雜湊表034-第乙個只出現一次的字元(python)

class

solution

: def fistnotrepeating

(self,s)

: dict=

for i in s:

dicts[i]

=dicts.

get(i,0)

+1for i in s:

if dicts[i]==1

:return i

return

-1

leetcode刷題 劍指offer 棧佇列堆

題目描述 class cqueue stack1.push value public int deletehead if stack2.isempty return 1 else return stack2.pop 沒有第二解法了,就這麼乙個辦法 題目描述 解法1 輔助棧,乙個棧完成push,pop...

劍指offer刷題日記 鍊錶

鍊錶03 從尾到頭列印鍊錶 python 採用insert方法 class solution def printlist self,listnode if not listnode return result while listnode result.insert 0 listnode.val l...

劍指offer刷題

面試題6 從尾到頭列印鍊錶 struct listnode class solution reverse res.begin res.end return res 替換空格class solution int newnumstr numstr numspace 2 if newnumstr leng...