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.

设计一个最小栈,使得返回栈中的最小数的这个操作的时间复杂度为常数,用双栈实现,一个栈作为最小数的保存栈,代码如下:

 class MinStack {
public:
void push(int x)
{
s.push(x);
if(sMin.empty() || x <= sMin.top())
sMin.push(x);
} void pop()
{
if(s.top() == sMin.top()){
sMin.pop();
}
s.pop();
} int top()
{
return s.top();
} int getMin()
{
return sMin.top();
}
private:
stack<int> s;
stack<int> sMin;
};

最新文章

  1. error CS0117: `UnityEditor.EditorUtility&#39; does not contain a definition for `GetAssetPreview&#39;
  2. bootstrap-datepicker的使用
  3. 常用的API接口,返回JSON格式的服务API接口
  4. CUBRID学习笔记 36 在net中添加多行记录
  5. iOS之沙盒机制和如何获取沙盒路径
  6. MyBatis学习总结_07_Mybatis缓存
  7. python执行mysqldump命令
  8. C语言——内存分配
  9. VS2010性能监视工具
  10. HOWTO install Oracle 11g on Ubuntu Linux 12.04 (Precise Pangolin) 64bits
  11. 使用git部署服务器
  12. 06 Activity 4中启动模式
  13. log | logstash
  14. Luogu P3366 【模板】最小生成树
  15. Cognos11中关于CJAP第三方认证的相关配置
  16. 三种常用的MySQL建表语句
  17. CocoaPods的安装及使用
  18. L1-023 输出GPLT
  19. windows运行打开服务命令
  20. 并发编程(四)TaskFuture

热门文章

  1. ThinkPHP语法总结
  2. CF1157D N Problems During K Days(简单构造)
  3. Python3.x:zip()函数
  4. 20145307JAVA学习期末总结
  5. 在Linux终端管理文件你要知道的11个命令
  6. Quick Search FAQ
  7. [转载]Javassist 使用指南(三)
  8. Fatal error compiling: java.lang.NoSuc hFieldError??
  9. 第七篇:Spark SQL 源码分析之Physical Plan 到 RDD的具体实现
  10. Chrome好用的插件:WhatRuns 查看网站使用的技术