博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode[155]-Min Stack
阅读量:7092 次
发布时间:2019-06-28

本文共 863 字,大约阅读时间需要 2 分钟。

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.


思路:须要两个栈,一个用来作为一般的栈,还有一个用来存放进栈到某一位置的当前站内最小元素。代码例如以下:

Code(c++):

class MinStack {public:    std::stack
stk; std::stack
min; void push(int x) { stk.push(x); if(min.empty() || (!min.empty() && x <= min.top())){ min.push(x); } } void pop() { if(!stk.empty()){ if(stk.top() == min.top())min.pop(); stk.pop(); } } int top() { if(!stk.empty()) return stk.top(); } int getMin() { if(!stk.empty()) return min.top(); }};

版权声明:本文博主原创文章,转载请注明出处。

你可能感兴趣的文章
w3c标准的selection对象介绍
查看>>
Python-类属性与对象属性之间的关系
查看>>
JavaScript 函数参数传递到底是值传递还是引用传递
查看>>
LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium...
查看>>
解决 No Entity Framework provider found for the ADO.NET provider
查看>>
转 用 Chrome 运行Android应用
查看>>
编程心得--不积跬步无以至千里
查看>>
thinkphp学习笔记8—命名空间
查看>>
在项目中几个需要学习的知识
查看>>
验证码安全问题汇总
查看>>
LINK : fatal error LNK1104
查看>>
WPF动态加载3D 放大-旋转-平移
查看>>
大型企业的渗透思路
查看>>
strace命令(收集整理,常看常新)
查看>>
Eclipse Console 加大显示的行数和禁止错误弹出
查看>>
$(document).height()与$(window).height()区别
查看>>
oracle字符集与客户端
查看>>
java线:辛格尔顿隐藏ThreadLocal实现线程数据共享
查看>>
MassTransit RabbitMQ 参考文档
查看>>
android 49 广播接收者中启动其他组件
查看>>