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 Data Structure

 

  这个是通过两个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 ;
}

最新文章

  1. zend studio面板功能
  2. 【统计学习】主成分分析PCA(Princple Component Analysis)从原理到实现
  3. Checkpoints codeforces 709B
  4. 通过布赛尔曲线以及CAShapeLayer的strokeStart 、strokeEnd 属性来实现一个圆形进度条
  5. hadoop 数据采样
  6. Android清空画布
  7. POJ3984 迷宫问题
  8. Java导出excel并下载功能
  9. 给一个非常长的字符串str 另一个字符集比方{a,b,c} 找出str 里包括{a,b,c}的最短子串。要求O(n)
  10. Linux搭建FastFDFS文件管理系统搭建,部署及上传材料
  11. 分布式锁的实现(redis)
  12. php的函数参数按照从左到右来赋值
  13. Java学习之运算符使用注意的问题
  14. js常用JSON数据操作
  15. #Java学习之路——基础阶段(第四篇)
  16. windows 下面安装make
  17. Python_sys.argv 命令行参数获取使用方法
  18. 东南亚 SAP 实施 马来西亚税收在SAP的设计和实现
  19. WEB框架本质和第一个Django实例
  20. (4)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Consul服务发现和消费

热门文章

  1. JavaScript 循环
  2. jupyter notebook(二)&mdash;&mdash;修改jupyter打开默认的工作目录
  3. HihoCoder - 1636 Pangu and Stones(区间DP)
  4. CountDownLatch、CyclicBarrier、Semaphore的区别
  5. LyaoutParameters作用
  6. Js中的假值_ES5中定义的ToBoolean方法强制类型转换后值为false
  7. cf975d Ghosts
  8. 【Luogu P1661】扩散
  9. IOS开发学习笔记011-xcode使用技巧
  10. 【LoadRunner】场景执行报错“failed: WSA_IO_PENDING”