当前位置:网站首页>第一讲:包含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(); */
边栏推荐
- Unity shader (pass user data to shader)
- Regular matching starts with XXX and ends with XXX
- LeetCode每日一题(2316. Count Unreachable Pairs of Nodes in an Undirected Graph)
- Using JWT to realize login function
- Pycharm create a new file and add author information
- Idea development environment installation
- Sublime Text4 download the view in bower and set the shortcut key
- Add new item after the outbound delivery order of SAP mm sto document is created?
- MongoDB怎么实现创建删除数据库、创建删除表、数据增删改查
- Information Security Experiment 1: implementation of DES encryption algorithm
猜你喜欢

Postman setting environment variables

How to pass the PMP Exam in a short time?

Postman interface debugging method

信息安全实验二 :使用X-SCANNER扫描工具

PMP Exam Preparation experience systematically improve project management knowledge through learning

Huawei HCIP - datacom - Core 03 jours

Netease cloud wechat applet

網易雲微信小程序

浏览器中如何让视频倍速播放

JMeter JDBC batch references data as input parameters (the simplest method for the whole website)
随机推荐
DRF defines views and routes
答案在哪里?action config/Interceptor/class/servlet
数据库多表关联查询问题
Unity shader (basic concept)
Information Security Experiment 3: the use of PGP email encryption software
消费互联网的产业链其实是很短的,它仅仅承接平台上下游的对接和撮合的角色
JVM garbage collection detailed learning notes (II)
牛客网——华为题库(61~70)
信息安全实验四:Ip包监视程序实现
Jenkins task grouping
The configuration and options of save actions are explained in detail, and you won't be confused after reading it
Netease Cloud Wechat applet
Network request process
Register address name mapping
Some pit avoidance guidelines for using Huawei ECS
華為HCIP-DATACOM-Core_03day
Windows starts redis service
Detailed learning notes of JVM memory structure (I)
Skill review of test engineer before interview
NATAPP内网穿透