今天的题都不难,算是基本操作.基本上要注意的一点就是活用函数去实现新的函数
232. Implement Queue using Stacks
这道题就是定义两个array/stack然后结合函数去实现ood
Way1:
class MyQueue(object):
def __init__(self):
self.q_in=[]
self.q_out=[]
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.q_in.append(x)
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
if self.q_out:
return self.q_out.pop()
else:
for _ in range(len(self.q_in)):
self.q_out.append(self.q_in.pop())
return self.q_out.pop()
def peek(self):
"""
:rtype: int
"""
tmp=self.pop()
self.q_out.append(tmp)
return tmp
def empty(self):
"""
:rtype: bool
"""
return not (self.q_in or self.q_out)
225. Implement Stack using Queues
这道题可以和上面一道题一样用两个deque去做,但是其实一个deque就够了
Way1:
直接建立deque,然后折腾value就行,注意pop前要判断是否empty
class MyStack:
def __init__(self):
self.q=deque()
def push(self, x: int) -> None:
self.q.append(x)
def pop(self) -> int:
if self.empty():
return None
for _ in range(len(self.q)-1):
self.q.append(self.q.popleft())
return self.q.popleft()
def top(self) -> int:
res=self.pop()
self.q.append(res)
return res
def empty(self) -> bool:
return not self.q