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.

使用一个栈,和一个保存最小值的变量min

栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小

利用差值使每个栈元素可以包含两个信息量

class MinStack {
public:
void push(int x) {
if (sta.empty())
{
sta.push();
min = x;
}
else
{
sta.push(x - min);
if (x < min)
min = x;
}
} void pop() {
if (sta.empty())
return;
long top = sta.top();
if (top < )
min = min - top;
sta.pop();
} int top() {
if (sta.empty())
return ;
long top = sta.top();
if (top < )
return min;
else
return min + top;
} int getMin() {
return min;
}
private:
stack<long> sta;
long min;
};

最新文章

  1. CC1310电源
  2. js方法收藏
  3. Yii 实现restful
  4. [Redux] Using withRouter() to Inject the Params into Connected Components
  5. [BZOJ 1033] [ZJOI2008] 杀蚂蚁antbuster 【模拟!】
  6. MVC中使用AuthorizeAttribute做身份验证操作【转】
  7. Oracle中使用透明网关链接到Sqlserver[Z]
  8. Oracle解锁的相关操作(转)
  9. 解决!同一ajax请求获取的图片路劲,在谷歌浏览器能正确展示图片,在火狐浏览器则显示路径undefined
  10. 在Windows上运行Linux
  11. Linux编译安装python3
  12. spring面向接口编程
  13. ActiveMQ在Windows下的安装与启动(懒人专属)
  14. powerdesigner-ER图建模
  15. Linux 查看内核版本命令的相关说明
  16. webbrowser打开新窗口事件+=
  17. Surface电池阈值
  18. Mongodb 分片操作 介绍
  19. BZOJ3295: [Cqoi2011]动态逆序对(树状数组套主席树)
  20. 2017-2018-1 20155318《信息安全技术》实验二——Windows口令破解

热门文章

  1. HTML 表单元素、 输入类型、Input 属性
  2. 查找子字符串----KMP算法深入剖析
  3. LINQ 的查询_联表、分组、排序
  4. ConcurrentHashMap原理
  5. ArcGIS API for JavaScript 4.2学习笔记[4] 第二章其余感兴趣的例子
  6. mysql学习之权限管理
  7. Java中Redis简单入门
  8. 使用SBT编译Spark子项目
  9. 一个web应用的诞生--数据表单
  10. js设置、获取、清除cookie