[LeetCode] Min Stack 栈
2024-10-10 02:54:04
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Hide Tags
这个是通过两个stack 维护,一个辅助栈support 维护非升序的情况,注意需要非升序,一个是用于全部data 维护。
#include <iostream>
#include <stack>
using namespace std; class MinStack {
public:
stack<int> data;
stack<int> support; void push(int x) {
if(data.empty()){
data.push(x);
support.push(x);
}
else{
data.push(x);
if(x<=support.top()) support.push(x);
}
} void pop() {
if(data.top()==support.top()) support.pop();
data.pop();
} int top() {
return data.top();
} int getMin() {
return support.top();
}
};
int main()
{
MinStack myMinStack;
myMinStack.push();
cout<<myMinStack.getMin()<<endl;
myMinStack.push();
cout<<myMinStack.getMin()<<endl;
myMinStack.push();
cout<<myMinStack.getMin()<<endl;
myMinStack.pop();
myMinStack.pop();
cout<<myMinStack.getMin()<<endl;
myMinStack.pop();
return ;
}
最新文章
- zend studio面板功能
- 【统计学习】主成分分析PCA(Princple Component Analysis)从原理到实现
- Checkpoints codeforces 709B
- 通过布赛尔曲线以及CAShapeLayer的strokeStart 、strokeEnd 属性来实现一个圆形进度条
- hadoop 数据采样
- Android清空画布
- POJ3984 迷宫问题
- Java导出excel并下载功能
- 给一个非常长的字符串str 另一个字符集比方{a,b,c} 找出str 里包括{a,b,c}的最短子串。要求O(n)
- Linux搭建FastFDFS文件管理系统搭建,部署及上传材料
- 分布式锁的实现(redis)
- php的函数参数按照从左到右来赋值
- Java学习之运算符使用注意的问题
- js常用JSON数据操作
- #Java学习之路——基础阶段(第四篇)
- windows 下面安装make
- Python_sys.argv 命令行参数获取使用方法
- 东南亚 SAP 实施 马来西亚税收在SAP的设计和实现
- WEB框架本质和第一个Django实例
- (4)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Consul服务发现和消费
热门文章
- JavaScript 循环
- jupyter notebook(二)&mdash;&mdash;修改jupyter打开默认的工作目录
- HihoCoder - 1636 Pangu and Stones(区间DP)
- CountDownLatch、CyclicBarrier、Semaphore的区别
- LyaoutParameters作用
- Js中的假值_ES5中定义的ToBoolean方法强制类型转换后值为false
- cf975d Ghosts
- 【Luogu P1661】扩散
- IOS开发学习笔记011-xcode使用技巧
- 【LoadRunner】场景执行报错“failed: WSA_IO_PENDING”