面试题 03.02. 栈的最小值
https://leetcode-cn.com/problems/min-stack-lcci/
维护一个最小值stack,每个元素对应当前位置下往前所有元素的最小值
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.sorted_stack = []
self.min_value = float('inf')
def push(self, x: int) -> None:
self.stack.append(x)
if x < self.min_value:
self.sorted_stack.append(x)
self.min_value=x
else:
self.sorted_stack.append(self.min_value)
def pop(self) -> None:
if not self.stack:
return None
res = self.stack.pop()
self.sorted_stack.pop()
if res == self.min_value:
self.min_value = float('inf') if not self.sorted_stack else self.sorted_stack[-1]
return res
def top(self) -> int:
if self.stack:
return self.stack[-1]
else:
return None
def getMin(self) -> int:
if self.sorted_stack:
return self.sorted_stack[-1]
else:
return None
剑指 Offer 59 - II. 队列的最大值
https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
from queue import Queue,deque
class MaxQueue:
def __init__(self):
self.queue = Queue()
self.deque = deque()
def max_value(self) -> int:
if self.deque:
return self.deque[0]
else:
return -1
def push_back(self, value: int) -> None:
while self.deque and self.deque[-1]<value:
self.deque.pop()
self.deque.append(value)
self.queue.put(value)
def pop_front(self) -> int:
if not self.deque:
return -1
res = self.queue.get()
if res == self.deque[0]:
self.deque.popleft()
return res
剑指 Offer 31. 栈的压入、弹出序列
https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/
场景还原:
新建一个临时stack,按照压栈顺序压入,每次压入后判断临时stack的最后一位和出栈序列的第一位是否相等,相等的话说明该弹出了,就持续弹出符合条件的元素,等循环结束后,如果临时stack和弹出序列都是空,那么就说明符合
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed and not popped:
return True
stack = list()
while pushed:
num = pushed.pop(0)
stack.append(num)
while stack and popped:
if stack[-1] == popped[0]:
popped.pop(0)
stack.pop()
else:
break
return not popped and not stack
331. 验证二叉树的前序序列化
https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree/
栈的消消乐
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
stack = []
for node in preorder.split(","):
stack.append(node)
while len(stack) > 2 and stack[-1]=='#' and stack[-2]=='#' and stack[-3].isdigit():
for i in range(3):
stack.pop()
stack.append('#')
return True if stack ==['#'] else False
入度和出度