二叉树后面是“堆、栈、队列”的题目,这节题目不算很多。感觉过不了多久就要到动态规划章节了,非常恐怖。

BM 43 包含min函数的栈

url:牛客 BM43

考察知识点:栈、最小值

这个题的最小函数处理还是比较巧妙,使用一个最小函数的辅助栈,每次插入元素时判断辅助栈栈顶元素与要插入的元素大小关系,如果小于栈顶元素则插入该元素,否则再次压入一个栈顶元素。通过这样的操作,把算最小元素的复杂度都分散到插入时了,还比较巧妙。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -*- coding:utf-8 -*-
class Solution:
stack = []
min_stack = []

def push(self, node):
# write code here
self.stack.append(node)

val = 10001 if len(self.min_stack) == 0 else self.min_stack[-1]
if node < val:
self.min_stack.append(node)
else:
self.min_stack.append(val)
def pop(self):
# write code here
self.min_stack.pop()
return self.stack.pop()
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.min_stack[-1]

BM44 有效括号序列

url:牛客 BM44

考察知识点:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return bool布尔型
#
class Solution:
def isValid(self , s: str) -> bool:
# write code here
stack = []

for i in range(len(s)):
if s[i] == "{":
stack.append("}")
elif s[i] == "[":
stack.append("]")
elif s[i] == "(":
stack.append(")")
elif s[i] in [")", "}", "]"]:
if len(stack) > 0 and stack[-1] == s[i]:
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False