diff --git a/notes/面试总结.md b/notes/面试总结.md index cc8f1dfd..6e4dfb66 100644 --- a/notes/面试总结.md +++ b/notes/面试总结.md @@ -32,6 +32,8 @@ * [27. 二叉树的镜像](#27-二叉树的镜像) * [28 对称的二叉树](#28-对称的二叉树) * [29. 顺时针打印矩阵](#29-顺时针打印矩阵) +* [30. 包含 min 函数的栈](#30-包含-min-函数的栈) +* [31. 栈的压入、弹出序列](#31-栈的压入弹出序列) * [参考文献](#参考文献) @@ -2185,6 +2187,111 @@ class Solution: return print_list ``` +# 30. 包含 min 函数的栈 + +[NowCoder](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 题目描述 + +定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的 min 函数。 + +## 解题思路 + +```java +private Stack dataStack = new Stack<>(); +private Stack minStack = new Stack<>(); + +public void push(int node) { + dataStack.push(node); + minStack.push(minStack.isEmpty() ? node : Math.min(minStack.peek(), node)); +} + +public void pop() { + dataStack.pop(); + minStack.pop(); +} + +public int top() { + return dataStack.peek(); +} + +public int min() { + return minStack.peek(); +} +``` + +```python +# -*- coding:utf-8 -*- +class Solution: + def __init__(self): + self.stack = [] + self.min_stack = [] + def push(self, node): + # write code here + self.stack.append(node) + if not self.min_stack or node <= self.min_stack[-1]: + self.min_stack.append(node) + def pop(self): + # write code here + if self.stack[-1] == self.min_stack[-1]: + self.min_stack.pop() + self.stack.pop() + def top(self): + # write code here + return self.stack[-1] + def min(self): + # write code here + return self.min_stack[-1] +``` + +# 31. 栈的压入、弹出序列 + +[NowCoder](https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking) + +## 题目描述 + +输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。 + +例如序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2 就不可能是该压栈序列的弹出序列。 + +## 解题思路 + +使用一个栈来模拟压入弹出操作。 + +```java +public boolean IsPopOrder(int[] pushSequence, int[] popSequence) { + int n = pushSequence.length; + Stack stack = new Stack<>(); + for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) { + stack.push(pushSequence[pushIndex]); + while (popIndex < n && !stack.isEmpty() + && stack.peek() == popSequence[popIndex]) { + stack.pop(); + popIndex++; + } + } + return stack.isEmpty(); +} +``` + +```python +# -*- coding:utf-8 -*- +class Solution: + def IsPopOrder(self, pushV, popV): + # write code here + if not pushV or len(pushV)!=len(popV): + return False + stack=[] + for i in pushV: + stack.append(i) + while len(stack) and stack[-1]==popV[0]: + stack.pop() + popV.pop(0) + if len(stack): + return False + return True +``` + # 参考文献 - 何海涛. 剑指 Offer[M]. 电子工业出版社, 2012.