当前位置:网站首页>第一讲:包含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(); */
边栏推荐
- 牛客网——华为题库(61~70)
- 如何使用clipboard.js库实现复制剪切功能
- Skill review of test engineer before interview
- 答案在哪里?action config/Interceptor/class/servlet
- Jenkins task grouping
- 战略合作|SubQuery 成为章鱼网络浏览器的秘密武器
- 创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同时,要求元素的值各不相同。
- SAP MM STO单据的外向交货单创建后新加ITEM?
- Nested (multi-level) childrn routes, query parameters, named routes, replace attribute, props configuration of routes, params parameters of routes
- 華為HCIP-DATACOM-Core_03day
猜你喜欢
VSCode+mingw64
Jenkins task grouping
嵌套(多级)childrn路由,query参数,命名路由,replace属性,路由的props配置,路由的params参数
NATAPP内网穿透
Locust performance test 2 (interface request)
Mysql数据库-锁-学习笔记
Information Security Experiment 2: using x-scanner scanning tool
Mysql:select ... for update
JVM garbage collection detailed learning notes (II)
答案在哪里?action config/Interceptor/class/servlet
随机推荐
Entity of cesium data visualization (Part 1)
12、 Sort
【云原生】DevOps(一):DevOps介绍及Code工具使用
C language pointer (exercises)
Huawei hcip datacom core_ 03day
The use of recycling ideas
Postman data driven
Summary of PMP learning materials
Schema-validation: wrong column type encountered in column XXX in table XXX
C language pointer (special article)
Cesium load vector data
esp8266使用TF卡并读写数据(基于arduino)
十二、排序
Mysql:select ... for update
PMP Exam details after the release of the new exam outline
Locust performance test 2 (interface request)
Pycharm create a new file and add author information
Data association between two interfaces of postman
Leetcode question brushing record (array) combination sum, combination sum II
How does the project manager write the weekly summary and weekly plan?