当前位置:网站首页>第一讲:包含min函数的栈
第一讲:包含min函数的栈
2022-07-07 06:51:00 【奋斗吧!骚年!】
题目:AcWing 41. 包含min函数的栈
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
push(x)–将元素x插入栈中
pop()–移除栈顶元素
top()–得到栈顶元素
getMin()–得到栈中最小元素
数据范围
操作命令总数 [0,100]。
样例
MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin(); --> Returns -4.
minStack.pop();
minStack.top(); --> Returns 3.
minStack.getMin(); --> Returns -1.
题目分析:
这道题如果没有返回最小值那么我们可以直接使用栈,那么如果需要返回最小值呢?
我们可以使用辅助栈
辅组栈只保存比栈顶元素小的元素,那么辅助栈的栈顶就是当前栈的最小值。
根据观看下图我们可以很直观感受到栈和辅助栈的关系。
即使 3 弹出栈,那么 41 将成为当前栈最小的值。
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
stk.push(x);
if(min_stk.empty()||min_stk.top()>=x)min_stk.push(x);
}
void pop() {
if(min_stk.top()==stk.top())min_stk.pop();
stk.pop();
}
int top() {
return stk.top();
}
int getMin() {
return min_stk.top();
}
private:
stack<int> stk,min_stk;
};
/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
边栏推荐
- Schema-validation: wrong column type encountered in column XXX in table XXX
- 章鱼未来之星获得25万美金奖励|章鱼加速器2022夏季创业营圆满落幕
- Pycharm create a new file and add author information
- Mysql database transaction learning notes
- SiteMesh getting started example
- Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]
- JMeter JDBC batch references data as input parameters (the simplest method for the whole website)
- Oracle安装增强功能出错
- Netease cloud wechat applet
- Postman interface debugging method
猜你喜欢
JMeter JDBC batch references data as input parameters (the simplest method for the whole website)
VSCode+mingw64+cmake
Pytest installation (command line installation)
Unity shader (basic concept)
What are the conditions for applying for NPDP?
[SVN] what is SVN? How do you use it?
Run can start normally, and debug doesn't start or report an error, which seems to be stuck
华为HCIP-DATACOM-Core_03day
章鱼未来之星获得25万美金奖励|章鱼加速器2022夏季创业营圆满落幕
Jmeters use
随机推荐
其实特简单,教你轻松实现酷炫的数据可视化大屏
PMP Exam Preparation experience, seek common ground while reserving differences, and successfully pass the exam
正则匹配以XXX开头的,XXX结束的
消费互联网的产业链其实是很短的,它仅仅承接平台上下游的对接和撮合的角色
Oracle安装增强功能出错
Port multiplexing and re imaging
Information Security Experiment 1: implementation of DES encryption algorithm
数据库多表关联查询问题
How to pass the PMP Exam in a short time?
What is the use of PMP certificate?
信息安全实验一:DES加密算法的实现
Mysql database index study notes
Postman setting environment variables
PMP certificate preparation experience sharing
Test Engineer Interview Questions 2022
MySQL common statements
Mysql数据库-锁-学习笔记
C language pointer (exercises)
How long does the PMP usually need to prepare for the exam in advance?
Regular matching starts with XXX and ends with XXX